Sunday, September 16, 2007

Rspec and Rspec::Rails install and usage

shell> gem install rspec

RSpec is a framework which provides programmers with a Domain Specific Language to describe the behaviour of Ruby code with readable, executable examples that guide you in the design process and serve well as both documentation and tests.

Here is how you do it
Start with a very simple example that expresses some basic desired behaviour.

# bowling_spec.rb
require 'bowling'

describe Bowling do
before(:each) do
@bowling =

it "should score 0 for gutter game" do
20.times { @bowling.hit(0) }
@bowling.score.should == 0

Run the example and watch it fail.

$ spec bowling_spec.rb
uninitialized constant Bowling

Now write just enough code to make it pass.

# bowling.rb
class Bowling
def hit(pins)

def score

Run the example and bask in the joy that is green.

$ spec bowling_spec.rb --format specdoc

- should score 0 for gutter game

Finished in 0.007534 seconds

1 example, 0 failures

Install Rspec::Rails
ruby script/plugin install svn://
ruby script/plugin install svn://
Once the plugin is installed, you must bootstrap your Rails app with RSpec. Stand in the root of your Rails app and run:
ruby script/generate rspec
This will generate the various files needed to use RSpec with Rails.
Run specs with rake …
rake spec
... or run specs with scripts/spec
ruby script/spec spec

No comments :