19

I'm working with Ruby on Rails 3, Cucumber, and Capybara

I've been searching for quite some time, and I can't figure out how to find a specific page element within a css tag. In my case, I need to make sure that a name is found inside of a table, and not in the "Welcome [Name]".

I tried something like:

within('table') do
  page.body.index("[Name]")
end

And I have a table with id='table'.

But I'd like to know how to do this for any css element, such as:

within('h2') do
  page.body.should have_content ('stuff')
end

I think my problem has to do with page.body, but I'm not sure how to contain it to a particular css tag.

Thanks in advance!

ardavis
  • 9,842
  • 12
  • 58
  • 112

4 Answers4

34

Capybara's within matcher only matches the first result, so if you have multiple h2 tags, it'll only look in the first one.

Instead, try have_css with the :text option.

page.should have_css("#table", :text => "[Name]")
page.should have_css('h2', :text => 'stuff')
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • This works, would there be a good way to get the index of that found element? So if I wanted to compare the order of two elements in a table, I think the best way would be to find the index of each, and compare them. – ardavis Nov 16 '11 at 21:00
12

To find a specific element:

page.find('#table').should have_text('stuff')
Paul Groves
  • 3,983
  • 2
  • 23
  • 24
  • 5
    have_text is no longer supported. Use page.find("#table").should have_content('stuff') instead. – y0mbo Jul 17 '13 at 17:35
4

I guess all answers should work but now Capybara doesn't use should anymore it uses expect

expect(page).to have_css("#table", :text => "[Name]")
expect(page).to have_css('h2', :text => 'stuff')
João Vitor
  • 111
  • 1
  • 8
0

I've done stuff like this: page.all(:css, 'button.btn-primary.days.active').size.should == 1

To check if there are any elements that contain a specific set of classes.
I didn't need to look for a particular text value of the element though. I just wanted to ensure the existence of the element, and how many of them there were.

Marnen Laibow-Koser
  • 5,959
  • 1
  • 28
  • 33
jacklin
  • 2,739
  • 1
  • 24
  • 31