How can I use Capybara to verify that the correct elements are specified?

I am trying to use Capybara to verify that the list contains the correct items. For instance:

<table id="rodents">
  <tr><td class="rodent_id">1</td><td class="rodent_name">Hamster</td></tr>
  <tr><td class="rodent_id">2</td><td class="rodent_name">Gerbil</td></tr>
</table>

This list should contain identifiers 1 and 2, but should not include 3.

I would like something like:

ids = ? # get the contents of each row first cell
ids.should include(1)
ids.should include(2)
ids.should_not include(3)

How can I do something like this?

I am responding with a few unsatisfactory solutions that I have found, but I would like to see the best.

+3
source share
4 answers

Here is a slightly simplified expression:

  rodent_ids = page.all('table#rodents td.rodent_id').map(&:text)

From there you can do your comparisons.

  rodent_ids.should include(1)
  rodent_ids.should include(2)
  rodent_ids.should_not include(3)
+7
source

Search for specific strings and identifiers

Bad solution:

within ('table#rodents tr:nth-child(1) td:nth-child(1)') do
  page.should have_content @rodent1.id
end

within ('table#rodents tr:nth-child(2) td:nth-child(1)') do
  page.should have_content @rodent1.id
end

page.should_not have_selector('table#rodents tr:nth-child(3)')

, id 3 .

+2

, :

  rodent_ids = page.all('table#rodents td:nth-child(1)').map{|td| td.text}

:

  rodent_ids.should include(1)
  rodent_ids.should include(2)
  rodent_ids.should_not include(3)

Or simply:

  rodent_ids.should eq(%w[1 2])
+2
source

Using has_table?

Bad solution:

  page.has_table?('rodents', :rows => [
                    ['1', 'Hamster'],
                    ['2', 'Gerbil']   
                  ]
                 ).should be_true

It is very clear to read, but:

  • It's fragile. If the table structure or text changes at all, it fails.
  • If it fails, it simply says that it expected false to be true; I don’t know an easy way to compare what the table really looks like expected exceptprint page.html
  • The method has_table? may be deleted at some point.
0
source

All Articles