Rails 2 and test/spec

We’ve been flirting with behavior-driven development here at the Labs recently, and have tried out RSpec and test/spec. Both have advantages, but I like test/spec a little more: it works well with existing Test::Unit tests and has a syntax I find more natural.

Somewhere along the path to Rails 2, test/spec stopped working well for me. New test classes — ActiveSupport::TestCase, ActionController::TestCase, and ActionMailer::TestCase — were introduced to eliminate repeated code in Rails tests, and test/spec classes, which inherit from Test::Unit::TestCase, suddenly didn’t transparently work.

Working on a personal project this weekend, I decided to figure out how to use test/spec again. Digging through its code, I found this gem:

def context(name, superclass=Test::Unit::TestCase, klass=Test::Spec::TestCase, &block) (Test::Spec::CONTEXTS[self.name + "\t" + name] ||= klass.new(name, self, superclass)).add(&block) end 

So now, if I want to use test/spec in my Rails tests, I just put the superclass after the context name, like so:

# For models context "User", ActiveSupport::TestCase ... end # For controllers context "User Controller", ActionController::TestCase ... end # For mailers context "User Mailer", ActionMailer::TestCase ... end 
Clinton R. Dreisbach

,
Posted in Article Category: #Code
on