Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Capybara to check that the correct items are listed?

Tags:

ruby

capybara

I'm trying to use Capybara to test that a list contains the correct items. For example:

<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 ids 1 and 2, but should not include 3.

What I'd like is something like:

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

How might I do something like that?

I'm answering with a couple of unsatisfactory solutions I've found, but I'd love to see a better one.

like image 399
Nathan Long Avatar asked May 09 '12 21:05

Nathan Long


2 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)
like image 62
Mark Thomas Avatar answered Nov 07 '22 03:11

Mark Thomas


Looking for specific rows and ids

A 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)')

This is verbose and ugly, and doesn't really say that id 3 shouldn't be in the table.

like image 32
Nathan Long Avatar answered Nov 07 '22 02:11

Nathan Long