12 December 2011

Acceptance testing Rails 3.1 application with minitest and Capybara

This post is about Rails 3.1 application acceptance testing with MiniTest::Spec and Capybara.
It is a continuation of my previous post. Please note that it covers only an acceptance spec example addition into already configured and working application, as described in previous post.

Add to your Gemfile:
group :test do
  gem 'capybara_minitest_spec

Don't forget to run bundler against your new Gemfile content:
$ bundle install

Add to your test/minitest_helper.rb:
require "capybara/rails"

# make url helpers, fixtures
# and capybara/dsl with matchers
# available within acceptance spec
class MiniTest::Rails::Acceptance < MiniTest::Rails::Spec
  include MiniTest::Rails::Fixtures
  include Capybara::DSL
  include Rails.application.routes.url_helpers

# make #describe BDD style available
MiniTest::Spec.register_spec_type /AcceptanceTest$/, MiniTest::Rails::Acceptance

Generate sample controller and view:
$ rails generate controller Website index
This should create some files for you.
Add sample content into app/views/website/index.html.erb:
<p>Hello Capybara!</p>

Config route in config/routes.rb:
get "website/index"

Create test/acceptance/website_test.rb with sample test:
require "minitest_helper"
describe "WebsiteAcceptanceTest" do
  it "website must be capybara friendly;)" do
    visit website_index_path
    page.must_have_content("Hello Capybara!")

Create new rake task within lib/tasks/test_acceptance.rake:
namespace :test do
  Rake::TestTask.new(:acceptance => "test:prepare") do |t|
    t.libs << "test"
    t.pattern = 'test/acceptance/**/*_test.rb'

Run all acceptance tests at once using:
$ rake test:acceptance

This post is based on some other sources. Please take a look at them to find more:

1 comment:

  1. For anyone viewing this article (which was a terrific help), I found that when defining the class MiniTest::Rails::Acceptance, you have to inherit from MiniTest::Spec instead of MiniTest::Rails::Spec as the article suggests. Otherwise, you get this error:

    /Users/xxxx/.rvm/gems/ruby-1.9.3-p194/gems/minitest-3.4.0/lib/minitest/spec.rb:68:in `describe': undefined method `create' for MiniTest::Rails::Acceptance:Class (NoMethodError).

    I'm new to minitest and capybara, and I was only able to solve this issue by looking at Jared Ning's article http://code-ningja.posterous.com/73460416.

    If anyone can clarify why, that would be a great help.