Monday, September 01, 2008

BDD - My First BDD Code using RSpec in Ruby

I am really really happy to see people putting so much efforts for building high quality, nearly all avoidable error free software. I am a big believer of Test Driven Development and doing TDD for about two years now. I have always had the feeling that TDD is a kind of a misnomer because to some people the term 'Test' refers to finding bugs. For this very reason, when people gets started with TDD, they consider it as a waste of time to write so much extra code that doesn't necessarily find bugs!

Well, a good vocabulary always makes it more attractive and useful. Now with BDD, Behavior Driven Development, I think the vocabulary that people actually codes the behaviors and implements the behaviors, not the tests, makes it more like it.

So, lets see my first ever written RSpec ruby code and the sexy html output!

#This is a poor Stack implementation

class Stack
def initialize
@items = []
end
def push(item)
@items << item
end
def pop
return nil unless @items && @items.length > 0
item = @items.last
@items.delete item
return item
end
def peek
return nil unless @items && @items.length > 0
@items.last
end
def empty?
@items.empty?
end
end

#This is the RSpec ruby code. Isn't is Simple?

describe Stack do
before(:each) do
@stack = Stack.new
end
describe "Empty" do
it "Should be empty when created" do
@stack.empty?.should == true
end
end
describe "With One Item (value = 3)" do
before(:each) do
@stack.push(3)
end
it "should not be empty" do
@stack.empty?.should be_false
end
it "should return the item (=3) when #peek" do
@stack.peek.should == 3
end
it "should return the item (=3) when #pop" do
@stack.pop.should == 3
end
end
end

Well, we all write codes and are doing this day and night for years. What I like to see is as sexy an output as the following from my source code :-)

RSpec

I know, you liked the output. For more you may check at http://rspec.info/

Need a similar solution on .Net? Keep Googling and come back to me if you see a good BDD tool. I would really like to use BDD in my .Net projects and see how better it performs over TDD.