Testing Rendered Views with RSpec2, Capybara and Rails 3.

While view tests are brittle, easily breaking when the design of a page changes, they are undoubtedly handy for checking the important parts of a page are rendered. I usually check for page titles, model attributes/tables or forms, and footer element, and so on.

Capybara is a great DSL for testing a page's rendered output, but unfortunately the Capybara matchers are not available in view or helper specs according to the rspec-rails documentation.

Thanks to this answer on Stack Overflow, it's possible to load a page's rendered content into a controller spec, and test it using the Capybara matchers.

I'm posting some example code here based on the answer for future reference, and to help anyone struggling to use Capybara with Rspec 2:

# Gemfile

group :test do
  gem 'capybara'
  gem 'rspec-rails'
end
# spec/controllers/users_controller_spec.rb

require 'spec_helper'

describe UsersController do
  # Render views and load the rendered content into Capybara for matching
  # See: http://stackoverflow.com/questions/4706370/rspec-view-testing-with-capybara-and-rails3/4773050#4773050#

  render_views

  let(:page) { Capybara::Node::Simple.new(@response.body) }

  describe "GET 'index'" do
    before { get :index }

    it { should respond_with(:success) }
    it { should assign_to(:users).with_kind_of(Array) }
    it { should render_template(:index) }

    # Test the rendered view using Capybara matchers
    it { page.should have_selector("h2") }
    it { page.should have_content("All Users") }
    it { page.should have_selector("table#users") }

    # ... add more tests ...

    it { page.should have_selector("div#footer" }
  end
end

Helpful post? Let me know by commenting on Twitter.