What I Like About RSpec
Posted by Lance Ivy Tue, 26 Aug 2008 03:00:00 GMT
Starting fresh projects is my favorite time to try new things. On this last project, it was RSpec. After looking at specs someone else wrote and playing around a bit, I’ve decided on what I like the most.
It’s the describe block.
Organization matters to me because it’s how I find my way around. It’s the principle of chunking, which is basically memory’s equivalent of keeping the code DRY. If I know how things should be organized, I can forget the details about how each instance is actually organized and reduce the burden on my memory.
Given how much tests can grow, organization is key to getting around later on. Here’s my basic approach to organizing tests for, say, an ActiveRecord model:
describe User do
describe "associations" do
end
describe "validations" do
end
describe "the foo method" do
end
endIt’s nothing spectacular—I generally have tests to make sure associations are set up properly, so those get chunked. And I always try throwing bad data at the validations to make sure those are set up properly, so those get chunked.
And, of course, a big bonus to chunking like this is that you can set up before blocks in each scope to DRY up your assertion preparations (e.g. mocking/stubbing/what-have-you so you can isolate a method).
Anyone else have favorite describe blocks?
Subscribe
The only thing I hate about RSpec is that it strings all the describe/specify blocks together when naming the test in the console, and there’s no way to turn it off. So you’re basically forced to make your test names form complete sentences, which is usually the furthest thing from my mind when writing tests, but apparently it’s pretty important to the BDD people. I guess I could always modify RSpec though so it doesn’t do that.
I’m pretty comfortable with broken sentences in the test printout. :-)