Joshua Muheim
Joshua Muheim

Reputation: 13195

RSpec/Capybara: Strange behaviour doesn't find <input type="hidden">, but it definitely is there

I have the following spec:

within dom_id_selector(@boilerplate_copy) do
  within '.copied_attributes_differing_from_original' do
    within 'form.title[action="http://www.textdiff.com/"]' do
      expect(page).to have_css 'button', text: 'Title'
      expect(page).to have_css 'input[name="string1"]'
      expect(page).to have_css 'input[name="string2"]'
    end
  end
end

Here is the HTML in question:

<div class="copied_attributes_differing_from_original">
  <form action="http://www.textdiff.com/" class="title" method="post" target="_blank">
    <input name="string1" type="hidden" value="Boilerplate Original test title">
    <input name="string2" type="hidden" value="Boilerplate Copy test title">
    <button type="submit">Title</button>
  </form>

  <form action="http://www.textdiff.com/" class="success_criterion_id" method="post" target="_blank">
    <input name="string1" type="hidden">
    <input name="string2" type="hidden" value="1">
    <button type="submit">Success criterion</button>
  </form>

  // More of them...
  <form action="http://www.textdiff.com/"...
</div>

While the first have_css passes (the button is found), the second have_css fails:

Failure/Error: expect(page).to have_css 'input[name="string1"]'
   expected to find css "input[name=\"string1\"]" but there were no matches. Also found "", which matched the selector but not all filters.

But in my opinion this element definitely is there! I also don't understand the output Also found "", which matched the selector but not all filters., what does it mean?

Thank you.

Upvotes: 1

Views: 680

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49890

By default Capybara doesn't find non-visible elements (which hidden inputs are) because a user can't see/interact with them. If you really need to check the presence of a non-visible element you can do

expect(page).to have_css('input[name="string1"]', visible: false)

That being said, since feature tests should be testing that the page functionality works rather than the details of exactly how it works you may not want to check for the presence of hidden inputs but rather just make sure the functionality they implement works.

Upvotes: 4

Related Questions