[英]Capybara Rspec Rails get ID for path
使用capybara / rspec测试导轨。 想要检查当前路径是否正确生成了ID,但无法访问创建的联系人ID。
预期示例:localhost:3000 / contacts / 27
收到的示例:localhost:3000 / contacts /
代码库:
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
有什么想法/想法吗?
您不能从功能测试中访问控制器实例变量。 不过,您可以访问数据库,并且由于您在此测试中仅创建了一个联系人,所以第一个或最后一个应该可以正常工作-
expect(page).to have_current_path(contact_path("#{Contact.last.id}"))
话虽如此,当您只为功能测试创建数据库记录时,仅在测试仅检查可以查看现有联系人的情况下注册用户并通过UI创建联系人并没有多大意义。 您可能想研究一下FactoryGirl来构建功能测试对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.