Inspecting the page content in Capybara

Updated . Posted . Visible to the public.

While you can use Capybara matchers like have_css and have_content for expectations, they are not too helpful for debugging. Here is how to view what Capybara is rendering.

Rendered text (what the user actually sees)

puts page.text

Prints just the visible text body, completely stripped of HTML tags and hidden elements.

Raw HTML

puts page.body

Prints the full HTML so you can inspect CSS classes, attributes, or missing elements.

If HTML output is cluttered with excessive blank lines, you can easily avoid printing them:

puts page.body.gsub(/^\s*$/, '').squeeze("\n")

Advanced DOM parsing with Nokogiri

If the raw HTML is too massive to read and you want to quickly extract a specific section without using Capybara's matchers, you can wrap page.body with Nokogiri:

document = Nokogiri::HTML(page.body)

This returns an object that you can interact with instead of just printing it to the console.
For example, use document.css() Show archive.org snapshot to get an array of Nokogiri Element instances that you can then filter further with Ruby.

Profile picture of Arne Hartherz
Arne Hartherz
Last edit
Arne Hartherz
Keywords
cucumber, rspec, minitest
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2010-12-16 10:47)