Monday, October 18, 2010

rails 3, rspec and webrat

This is a small sample setup for rails 3 rspec-rails 2 and webrat.
It uses webrat for acceptance tests of a simple sacaffolded model.

Here are the steps:

create a new rails project

$ rails new testwebrat -d postgresql
$ cd testwebrat

edit the Gemfile

group :development, :test do
  gem 'rspec', '>= 2.0.0'
  gem 'rspec-rails', '>= 2.0.0'
  gem 'webrat'
end

install the missing bundles

$ bundle install

let the rspec files generate

$ rails g rspec:install


as a quick sample, generate a new scaffold User

$ rails g scaffold User name:string

do the migrations

$ rake db:migrate

start the server to see everything is working

$ rails s

write the webrat test in file rspec/requests/users_spec.rb

describe 'Managing users' do

  it 'should enable the creation of a new entity' do
    visit users_path

    response.should contain 'Listing users'
    response.should_not contain 'Show'
    response.should_not contain 'Edit'
    response.should_not contain 'Destroy'
    response.should have_selector 'a', :content => 'Destroy', :count => 0
    response.should have_selector 'a', :href => new_user_path, :content => 'New User'

    click_link 'new User'
    fill_in 'user[name]', :with => 'my_type'
    click_button 'Create User'

    response.should contain 'was successfully created.'
    response.should have_selector 'p', :content => 'my_type'

    click_link 'Back'

    response.should contain 'Listing users'
    response.should have_selector 'table tr', :count => 2

    response.should have_selector 'table tr:last-child td:first-child', :content => 'my_type'
    response.should contain 'Show'
    response.should contain 'Edit'
    response.should contain 'Destroy'
  end

  it 'should enable the deletion of an entry' do
    visit users_path
    click_link 'new User'
    fill_in 'user[name]', :with => 'my_type'
    click_button 'Create User'

    response.should contain 'was successfully created.'
    response.should have_selector 'p', :content => 'my_type'

    click_link 'Back'

    response.should contain 'Listing users'
    response.should have_selector 'a', :content => 'Destroy', :count => 1

    click_link 'Destroy', :method => :delete, :javascript => true

    response.should contain 'Listing users'
    response.should_not contain 'Show'
  end

end

run the rspec request tests

$ rake spec:requests

No comments: