Search code examples
ruby-on-railsrspeccapybararspec-rails

Error when writing RSpec Test Capybara::ElementNotFound: Unable to find field


I am writing RSpec Tests for a view and getting the following error when trying to fill in a text field.

1) coordinators/new.html.erb populate page name text entry field filled checks for presence of filled in text field
 Failure/Error: fill_in "coordinator_name", with: 'JoeJoe'

 Capybara::ElementNotFound:
   Unable to find field "coordinator_name"
 # ./spec/views/coordinators/new.html.erb_spec.rb:47:in `block (4 levels) in <top (required)>'

Here is part of my code, including the preceding test where the field "coordinator_name" is found. I am confused as to why it's not found in the 2nd test?

describe 'name text entry field' do
  it 'checks for presence of empty text field for name' do
   expect(rendered).to have_field('coordinator_name', text: nil)
  end
end

describe 'name text entry field filled' do
  it 'checks for presence of filled in text field' do
    fill_in "coordinator_name", with: 'JoeJoe'
    expect(rendered).to have_field('coordinator_name', text: 'JoeJoe')
  end
end

Any suggestions on how to find a solution?


Solution

  • The issue here is that you're writing a view test - A view test can check for content on the page but it can't interact with it. In a normal setup the capybara matchers would be included in your view specs, but the Capybara::DSL would not be - https://github.com/teamcapybara/capybara/blob/master/lib/capybara/rspec.rb#L10 - so fill_in should not even be available in the view spec. I'm assuming you've overridden that by including Capybara::DSL in all your specs?

    For you second spec to work you need to write a feature spec.