Wednesday, April 16, 2008

Please teach me rspec

I was first introduced to BDD like 4 years back by Dave Astel's article. I really liked the idea. It totally made sense to me. I was like damn this is the way we have to think for designing objects. That time I was working in a java project. Igor and I were like okay lets do BDD and started naming our Junit test methods like testDogShouldBarkWhenThrownStoneAt . When jBehave released I wanted to use it, but I never got a chance.

When I started working on yewoh, I was so excited that now I can chose whatever framework I want. Being a BDD addict, I obviously chose rspec. It is a great framework for doing BDD.It gives you nice syntax to express behaviors in "when" and "should" format .It felt very natural for me to write verifications for verifying my object behavior instead of tests.

Now after using rspec for sometime, I have some questions about rspec.

  • What is the best way to organize specs? In rails project, specs are arranged in folders like models, controllers etc. I do not have a problem arranging the spec files, but I am not sure how to organize specs itself. Does anyone has some good practices that worked for them?
  • Sometimes my objects have behaviors like "Player When power is on It should start playing When play button is pressed " . In this behavior I have two When conditions. How do you express this behavior in rspec ? Should I have it like


describe Player, "When play button is pressed"
it "should start playing if power is on"
....
end
end

using a if condition. Or should I have something like this

 describe Player, "When power is on and play button is pressed"
it "should start playing"
...
end
end
  • In unit test, usually we write tests to make sure our method do not blow up when we pass nil for example. I feel it is a good test to have. How do we writes spec for this kind of situations?  
Rspec documentation has good explanations and examples for rspec syntax. But I am looking for best practices for using rspec.

It will be great if you all share your experience with rspec.

4 comments:

Luke said...

I would write your example like this.

Siva Jagadeesan said...

Thanks Luke for ur response. But still I feel there should be a better way to specify. It will be nice if we can specify somewhat like "Given , When , It" format.

Matt V said...
This comment has been removed by the author.
Matt V said...

my take is a little different:
http://pastie.textmate.org/247120