Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara: how to check the TEXT value of an element with xpath and css?

Tags:

capybara

Trying to make this test to fail without success.

I've got this HTML:

<div id="navigation">
 <ul>
  <li>
   <a href="/url">TV</a>

And then I was trying to identify the text of the A element and make it fail for now.

I've used all the following expressions with Xpath but all of them keep passing even though I'm using a different text for the comparison :S

page.should have_xpath("//div[@id='navigation']//a", :content => 'Radio')
page.should have_xpath("//div[@id='navigation']//a", :text => 'Radio')
page.should have_xpath("//div[@id='navigation']//a[contains(string(),'Radio')]")
page.should have_xpath("//div[@id='navigation']//a[contains(text(),'Radio')]")
page.should have_xpath("//div[@id='navigation']//a[contains(.,'Radio')]")

Any idea how I could identify the text of an specific HTML element with capybara? and... is it possible to achieve the same with CSS?

Cheers!

like image 516
mickael Avatar asked Dec 12 '12 23:12

mickael


2 Answers

As of RSpec 2.11 (July 2012), the preferred way is to use the expect syntax:

expect(page).to have_css("#navigation a", text: "Radio")

You can configure RSpec to only accept this new syntax to keep your codebase consistent.

like image 126
Jan Klimo Avatar answered Nov 17 '22 04:11

Jan Klimo


It turns out that there was another element with the text 'Radio' in the 'navigation' DIV, so that was causing the test to fail.

For future reference, identifying the 1st element explicitly behaved as expected and fails the test:

page.first('div#navigation a').text.should == 'Radio')
page.first('div#navigation a').text.should eq('Radio')
page.first('div#navigation a').text.should match('Radio')
page.first('div#navigation a').text.should be('Radio')
like image 12
mickael Avatar answered Nov 17 '22 05:11

mickael