more BDD and RSpec…

November 4th, 2007

“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.”
…in RSpec

This is, RSpec is a state of mind in Ruby, represented in a DSL (Domain Specific Language for Behaviour Driven Development (BDD). It deals with expressing desired behaviours when building applications, creating the specifications and writing the code to match them.
Create examples for what the application should do, and build the code. Add another example, write more code, refactor it if necessary, and:

$/var/lib/gems/1.8/bin/spec app_spec.rb --format specdoc
RSpec rdoc
RSpec documentation

This is a work in progress but means a refactor on the way to think about developing…
Example: For us to be able to drive a car:
- it should have fuel;
- its battery should be charged;
- it should have at least 4 tyres (optimally a spare one), with the right pressure;
- …

require 'car'
describe Car do
   before(:each) do
     @car = Car.new
   end
 
   it "should not be out of fuel" do
     @car.should_not be_fuel(0)
   end
 
   it "should have a charged battery" do
     @car.batt(0.6).should be_close(1, 0.5)
   end
 
   it "should have at least 4 tyres" do
     @car.should have_at_least(4).tyres
   end
 
   after(:each) do
     @car = nil
   end
 
end

Now, in car.rb:

class Car
 
   def fuel?(qt)
     qt > 0
  end
 
   def batt(amp)
     @amp = amp
   end
 
   def tyres
     { 'fr' => 2.1, 'fl' => 2.1, 'rr' => 2.0, 'rl' => 2.0, 's' => 2.1 }
   end
 
end

Ok, running this small spec:

$ /var/lib/gems/1.8/bin/spec car_spec.rb --format specdoc
 
Car
- should not be out of fuel
- should have a charged battery
- should have at least 4 tyres
 
Finished in 0.014326 seconds
3 examples, 0 failures

Now, what about using BDD RSpec module with Camping… ?


2 Comments to “more BDD and RSpec…”


  1. Ruben Fonseca said:

    I have recently discovered this RSpec thing and I must say I’m in love. I actually bought one of the RSpec screencasts on PeepCode!

    I always thought that TDD was too geeky for me, but this BDD really makes my style! Love the Ruby implementation too… Have you tried the Rails helpers on a Rails application? Just sweet…


  2. pedro said:

    Ruben, i find TDD simple and a bit boring… assert… assert…

    BDD is more specification driven. Its almost phylosophycal.
    Did you see the Story plugin ? Is the path for RSpec, poetry specifications ?

Leave a Reply