Read more

How to grep through the DOM using the Capybara API

Henning Koch
July 28, 2011Software engineer at makandra GmbH

When your Cucumber feature needs to browse the page HTML, and you are not sure how to express your query as a clever CSS or XPath expression, there is another way: You can use all Show archive.org snapshot and find Show archive.org snapshot to grep through the DOM and then perform your search in plain Ruby.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Here is an example for this technique:

Then /^I should see an image with the filename "([^\"]*)"$/ do |filename|
  patiently do
    page.all('img').find do |img|
      img[:src].include?("/#{filename}")
    end.should be_present
  end  
end

Note that the check needs to be wrapped in a patiently helper since the DOM might change between page.all('img') and the check img[:src].include?, causing a Selenium::WebDriver::Error::StaleElementReferenceError.

Of course if you can express a check in a readable CSS query, you should always do so. It does not need patiently since it is executed in a single Selenium command:

Then /^I should see an image with the filename "([^\"]*)"$/ do |filename|
  page.should have_css("img[src*='/#{filename}']")
end
Posted by Henning Koch to makandra dev (2011-07-28 18:07)