RSpec for Ruby on Rails

Behaviour driven development is currently in. The best ay how to get in touch with it is to setup your own environment and make few examples.Nevertheless, if you prefer to start with a bit of theory, go to http://behaviour-driven.org/.This article describes simple procedure to setup Rspec to work together with ruby on rails.

Installation of RSpec

The installation procedure described in documentation needed small improvement:

First of all, install the rspec gem

gem install -r rspec #mac users must sudo

Then install following gems:

  • rake # Runs the build script
  • rcov # Verifies that the code is 100% covered by specs
  • webgen # Generates the static HTML website
  • RedCloth # Required by webgen
  • syntax # Required by our own custom webgen extension to highlight ruby code
  • diff-lcs # Required if you use the -diff switch
  • win32console # Required by the -colour switch if you‘re on Windows
  • meta_project # Required in order to make releases at RubyForge
  • heckle # Required if you use the -heckle switch
  • hpricot # Used for parsing HTML from the HTML output formatter in RSpec’s own specs

Then continue with these steps:

svn co svn://rubyforge.org/var/svn/rspec/trunk rspec
cd rspec
rake install_dependencies
cd example_rails_app
export RSPEC_RAILS_VERSION=1.2.3
rake rspec:generate_mysql_config
mysql -u root -p < db/mysql_setup.sql
cd ..change example_rails_app/config/database.yml to correspond to your configurationrake pre_commit

and…Make the first test.

Create new folder in your project called spec. Create a file named e.g. basic_test.rb and fill it with

describe "Sum computation" do  
  it "should return 2" do    
    (1+1).should == 2  
  end
end

run it with

spec spec/basic_test.rb

Your test should finish sucessfuly:

.Finished in 0.006001 seconds1 example, 0 failures

Working with rails

That’s great! Now, let’s make it running with your rails objects. Go to the root of your application and install rspec plugins:

ruby script/plugin install svn://rubyforge.org/var/svn/rspec/tags/CURRENT/rspec
ruby script/plugin install svn://rubyforge.org/var/svn/rspec/tags/CURRENT/rspec_on_rails

bootstrap your application with

ruby script/generate rspec

and start testing with the rails objects. Use rspec generator to create the first test:

ruby script/generate rspec_model user

It generates file spec/models/user_spec.rb file

require File.dirname(__FILE__) + '/../spec_helper'
describe User do  
  before(:each) do    
    @user = User.new  
  end  

  it "should be valid" do    
    @user.should be_valid  
  end
end

And now you can just extend the pre-generated file and enjoy it.

5 comments

  1. not like ruby script/generate rspec_model user
    you have to use this rspec something like following.

    ruby script/generate rspec_scaffold User :name => :stirng, :phone => :integer, :….

    Wel Come In Advance

Comments are closed.