Skip to content

Instantly share code, notes, and snippets.

@gabehollombe
Created May 20, 2010 06:26
Show Gist options
  • Save gabehollombe/407265 to your computer and use it in GitHub Desktop.
Save gabehollombe/407265 to your computer and use it in GitHub Desktop.
Capybara: a better way to check if text is visible
### IMPORTANT NOTE: See the comment thread below for a more concise way to determine this now, using has_css...
#A better 'I should not see' for Capybara that lets jQuery determine visibility of the text you're looking for.
Then /^"([^\"]*)" should not be visible$/ do |text|
finder_script = %{
function is_text_visible_on_page(text) {
var match = false;
$('*:visible')
.contents()
.filter(function() {
//collect text nodes
return this.nodeType === 3;
})
.each(function() {
if (this.textContent.indexOf(text) != -1) {
match = true;
return false;
}
});
return match;
}
is_text_visible_on_page('#{text}');
}
assert ! page.driver.evaluate_script(finder_script)
end
@gerryster
Copy link

The logic looks reversed in this example.

@gabehollombe
Copy link
Author

@gerryster Possibly so. This is an old script and I'm not using it anymore. These days I'm using:

Then /^"([^"]*)" should not be visible$/ do |text| begin assert page.find(text).visible? != true rescue Capybara::ElementNotFound end end

@ctide
Copy link

ctide commented Dec 1, 2011

I'm guessing you're using something even newer now since that version doesn't work? :)

@gabehollombe
Copy link
Author

@ctide: yep. These days I'm not using cucumber at all, and just using rspec with capybara directly, like:

page.should have_no_css('a', :text => 'foo', :visible => true)

@BSierakowski
Copy link

+1, this works very well. Confused me at first, but I scoped this within the location, then if the thing exists use the above line to make sure the "page has no css with that text that's visible."

Wound up making a helper like this:

  def restaurant_should_be_hidden(location, text)
    within(location) do
      if page.has_content?(text)
        page.should have_no_css('a', :text => text, :visible => true)
      end    
    end
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment