Close and Go BackBack to Viget

Rails 2 and test/spec

Clinton R. Nixon
Clinton R. Nixon, Senior Developer, March 24, 2008 1

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
Josh Adams said on 05/13 at 05:38 PM

Can I ask why you wouldn’t just monkeypatch it with a file in /lib?  That’s what I’d tend to do in that situation, as the method signature is unlikely to change between major versions.

Name:

Email:

URL:

Not a robot? Prove it by entering the word below.


Remember my personal information

Notify me of follow-up comments?

Next entry: cURL and Your Rails 2 App

Previous entry: When Cookies Fail

A Development Community for Viget Labs and Beyond

Every team member here at Viget Labs strives to be an innovator. We members of the development team are no different - that's why we're constantly engaging in community discussions and exploring the unknown that is the next generation of open-source web applications.

Viget Is Hiring!

Viget has job openings for Ruby Developers, Interns, and Front-End Developers. Learn More »

Recent Comments

Interesting.

I’ve been (mis)using similar behaviour in javascript for years.


var i = 0, car;
while( car = cars[i++]){
// do stuff
}

I suppose that the reason it works is exactly the same reason it works in Ruby ... but in this case I think the code is actually very easy to read.