Overview

RSpec is a framework that 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.

# game_spec.rb
require 'game'

describe Game do
  before(:each) do
    @game = Game.new
  end

  it "should score 0 for gutter game" do
    1.upto(20) { @game.hit(0) }
    @game.score.should == 0
  end
end

Run the example and watch it fail.

$ spec game_spec.rb 
./game_spec.rb:4:
  uninitialized constant Game

Now write just enough code to make it pass.

# game.rb
class Game
  def hit(pins)
  end

  def score
    0
  end
end

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

$ spec game_spec.rb --format specdoc

Game
- should score 0 for gutter game

Finished in 0.007534 seconds

1 example, 0 failures

Take very small steps

Don’t rush ahead with more code. Instead, add another example and let it guide you to what you have to do next. And don’t forget to take time to refactor your code before it gets messy. You should keep your code clean at every step of the way.

Take the first step now!

$ gem install rspec