简体   繁体   中英

Capybara Rspec Rails get ID for path

Using capybara/rspec to test rails. Want to check current path is generated correctly with the id but cant access the created Contact id.

Example expectation: localhost:3000/contacts/27

Example recieved: 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. Clearly it cant access the 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. But throws error 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. You probably want to look into something along the line of FactoryGirl for building your feature test objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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