Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara have_field not finding field found by have_selector

I'm currently writing a Cucumber feature for a messaging system in a Rails app. This is one of my steps.

Then(/^they should see the message displayed in their language$/) do
  id = "message_to_#{@family.id}"
  expect(page).to have_selector("textarea##{id}")
  save_and_open_page
  expect(page).to have_field(id, type: :textarea)
end

The first assertion passes, but the second fails. When I inspect the markup created by save_and_open_page, the following element is present:

<textarea cols="22" disabled="disabled" id="message_to_13" name="body" placeholder="Hallo, Ich bin sehr interessiert an deinem Profil. Würdest du gerne mit mir in Kontakt treten?" rows="7"></textarea>

The error message displayed for the second test is:

expected to find field "message_to_13" but there were no matches. Also found "", which matched the selector but not all filters. (Capybara::ExpectationNotMet)

I'm tearing my hair out here to understand why Capybara can find this element that is obviously present using have_selector, but not with have_field?

like image 379
Richard Stokes Avatar asked Aug 25 '13 18:08

Richard Stokes


1 Answers

The problem is that the textarea has the disabled="disabled" attribute, meaning it is a disabled field. By default, Capybara ignores disabled fields. New in Capybara 2.1 is the option to look for disabled fields.

Adding the disabled: true option will solve your problem:

expect(page).to have_field(id, type: 'textarea', disabled: true)

Note:

  • That when you include disabled: true, the field must be disabled. The default is disabled: false, which only matches fields that are not disabled.
  • That the :type value should be a string. As seen in the above, it is type: 'textarea'). Using a symbol, type: :textarea will not work.
like image 144
Justin Ko Avatar answered Nov 14 '22 23:11

Justin Ko