简体   繁体   English

Capybara Rspec Rails获取路径的ID

[英]Capybara Rspec Rails get ID for path

Using capybara/rspec to test rails. 使用capybara / rspec测试导轨。 Want to check current path is generated correctly with the id but cant access the created Contact id. 想要检查当前路径是否正确生成了ID,但无法访问创建的联系人ID。

Example expectation: localhost:3000/contacts/27 预期示例:localhost:3000 / contacts / 27

Example recieved: localhost:3000/contacts/ 收到的示例:localhost:3000 / contacts /

Code base: 代码库:

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

Surprised the interpolation hasn't worked and throws error undefined method 'id' for NilClass using the below. 惊讶的是插值没有起作用,并使用以下方法为NilClass抛出错误未定义的方法'id'。 Clearly it cant access the id. 显然,它无法访问ID。

expect(page).to have_current_path(contact_path("#{@contact.id}"))

Also tried swapping it out with @p = Contact.find_by_id(params[:id]) then passing in the @p in the interpolation. 还尝试将其替换为@p = Contact.find_by_id(params[:id])然后在插值中传入@p。 But throws error undefined local variable or method params 但是抛出错误undefined local variable or method params

Any ideas/thoughts? 有什么想法/想法吗?

You can't access your controllers instance variables from within a feature test. 您不能从功能测试中访问控制器实例变量。 You can however access the database, and since you've only created one contact in this test first or last should work - 不过,您可以访问数据库,并且由于您在此测试中仅创建了一个联系人,所以第一个或最后一个应该可以正常工作-

expect(page).to have_current_path(contact_path("#{Contact.last.id}"))

That being said, signing up a user and creating the contact through the UI when your test is only checking that an existing contact can be viewed doesn't make a lot of sense when you could just create the database records for your feature tests. 话虽如此,当您只为功能测试创建数据库记录时,仅在测试仅检查可以查看现有联系人的情况下注册用户并通过UI创建联系人并没有多大意义。 You probably want to look into something along the line of FactoryGirl for building your feature test objects. 您可能想研究一下FactoryGirl来构建功能测试对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM