【发布时间】:2016-05-06 13:38:52
【问题描述】:
使用 capybara/rspec 来测试 rails。想要使用 id 检查当前路径是否正确生成,但无法访问创建的联系人 id。
示例期望: 本地主机:3000/contacts/27
收到的示例: 本地主机:3000/联系人/
代码库:
feature 'contacts' do
before do
visit '/'
click_link 'Sign up'
fill_in 'Email', with: 'test@test.com'
fill_in 'Password', with: '123456'
fill_in 'Password confirmation', with: '123456'
click_button 'Sign up'
click_link 'Add a contact'
fill_in 'Firstname', with: 'John'
fill_in 'Surname', with: 'Jones'
fill_in 'Email', with: 'test@test.com'
fill_in 'Phone', with: '223344'
attach_file('contact[image]', Rails.root + 'spec/mouse1.jpeg')
click_button 'Create Contact'
end
context 'view a contact' do
scenario 'click contact to view details' do
click_link('Mouse1')
expect(page).to have_content 'John Jones 223344 test@test.com'
expect(page).to have_xpath("//img[contains(@src, \/html/body/a[2]/img\)]")
expect(page).to have_current_path(contact_path("#{@contact.id}"))
end
end
惊讶于插值没有起作用,并使用下面的方法为 NilClass 抛出错误未定义的方法 'id'。显然它无法访问 id。
expect(page).to have_current_path(contact_path("#{@contact.id}"))
还尝试将其换成@p = Contact.find_by_id(params[:id]),然后在插值中传入@p。但抛出错误undefined local variable or method params
有什么想法/想法吗?
【问题讨论】:
-
变量
@contact.id在哪里定义? -
hi @Зелёный 在 contacts_controller.rb 中。
-
为什么您认为可以在功能测试中从控制器访问实例变量 (
@contact)?你不能。 -
我认为它可以访问。是否可以访问数据库以检索 URL 的 ID?或者这是不可能的?其次,您将如何测试创建的 URL 是否正确?
-
你试过
Contact.last.id吗?
标签: ruby-on-rails rspec path capybara