Wednesday, April 18, 2007

RSpec

I been using RSpec for about 1 week now. I must say I really love it. Anyone who has worked with me knows I'm a test-first style developer. Now I switched to a spec-first developer!

RSpec is a ruby library for Behavior Driven Development (BDD). It accomplishes the same purpose as Unit Testing, automated tests for development. The big difference is BDD changes the way you think about tests.

With BDD, you begin by defining a "context" which is a situation or state of the system under test. For example, for a Stack object one context would be an "empty stack".

Next, you define the "specifications" for the "context". BDD uses language such as "should be", "should not" to describe the specification. In the "empty stack" context, the specification might include "should be empty", and "pop should throw exception". Within the specification we add the test code to check that the specification is followed. Here is the ruby code for this example:

context "A new stack" do

setup do
@stack = Stack.new
end

specify "should be empty" do
@stack.should be_empty
end

specify "pop must throw exception" do
lambda { @stack.pop }.should raise_error
end
end


Notice how easy it is to read the code above. This is what I like about RSpec verses xUnit. The contexts and specifications provide guidance about how to orginize your tests.

RSpec does not stop there. RSpec also includes RCov so you can easily see a report of test coverage. This is very handy to find holes in your specifications and tests. RSpec includes a mock object framework to help isolate the system under test. You can also use the mock objects to test the object interation of the system under test. RSpec does support Rails development.

Anyone interested in learning Behavior Driven Development or RSpec, I highly recommend working through the RSpec tutorial. The tutorial really provides a great exercise in BDD. I had read about BDD, but it wasn't until I completed the tutorial that I internalized it. (If you need Ruby, you can download it from ruby-lang.org, I use the Windows One-Click Install. Then type "gem install rspec" on the command-line to get rspec. Very quick and easy!)

No comments: