---
title: Use Capybara On Any HTML Fragment Or Page
teaser:
tags: web,testing,ruby,rails
author: Nick Quaranto
published_on: 2011-07-26
---

![capybaras are pretty classy](https://img.skitch.com/20110726-narpmkn94319a161keubi15yyu.png)

I was upgrading [Gemcutter](http://github.com/rubygems/gemcutter) to Cucumber
and Capybara 1.0 yesterday from Webrat (a change long overdue!), and I
discovered a neat little class within Capybara that is worth sharing.
Basically, since I was moving the app from Webrat, matchers like
`assert_contain` and `assert_have_selector` are no longer available. Capybara's
`Node` class has a great `Matchers` mixin with [tons of
goodies](http://rdoc.info/gems/capybara/1.0.0/Capybara/Node/Matchers) that can
be used like so, in RSpec:

    page.should have_content("This should be on the page")
    page.should have_selector("a[href='http://thoughtbot.com']")

Great, but how does one use that in functional/controller tests?

Enter `Capybara::Node::Simple`, which I found purely by chance when source
diving. This class'
[docs](http://rdoc.info/gems/capybara/1.0.0/Capybara/Node/Simple) proclaim its
usefulness:

> It is useful in that it does not require a session, an application or a
> driver, but can still use Capybara’s finders and matchers on any string that
> contains HTML

Bingo! Now, how to use in our test suite? We're still on Test::Unit for
Gemcutter, so I had to do the following in `test/test_helper.rb`:

    class Test::Unit::TestCase
      def page
        Capybara::Node::Simple.new(@response.body)
      end
    end

Now the Gemcutter test suite can do assertions like so:

    assert page.has_content?("Rails (3.0.9)")
    assert page.has_selector?("a[href='/gems/rails/versions/3.0.9']")

The whole diff is [on
GitHub](https://github.com/rubygems/rubygems.org/commit/1a6a38c8d7515b7a00d4749fa1f3c638fb7e4a32)
if you'd like to see all of the changes of moving our functional tests from
Webrat to Capybara.

[Gabe](http://thoughtbot.com/about/#gberkewilliams) also found out that there's
also a shortcut in Capybara for creating a `Simple`: `Capybara.string`. The
[docs](http://rdoc.info/gems/capybara/1.0.0/Capybara#string-class_method) for
this show that it's basically sugar on top of the `Simple` initializer:

    node = Capybara.string <<-HTML
      <ul>
        <li id="home">Home</li>
        <li id="projects">Projects</li>
      </ul>
    HTML

    node.find('#projects').text # => 'Projects'

I think this pattern is really useful not just for upgrading suites from Webrat,
but really anywhere you have an <abbr title="HyperText Markup
Language">HTML</abbr> fragment or string that you'd like to use Capybara's
matchers on.
