test/spec/rails => You Bettuh Recognize

Published on Friday, February 08, 2008 in rails, ruby, and testing

Believe it or not, there are still at least a few of us crazy hold-outs that still haven’t imbibed the increasingly ubiquitous RSpec Kool-Aid. And for the folks in this crowd that still want BDD-style testing, it’s test-spec and test/spec/rails all the way. So when I recently needed a means for validating that a nontrivial route landed in the right controller/action, I naturally went looking for the test/spec/rails equivalent of #assert_recognizes. When I saw that it was nowhere to be found, I knew I’d found another task for Open Source Fridays (er, the first half hour of an Open Source Friday). And thanks to Matthew Bass’s uncanny responsiveness in applying the patch that Rob Sanheim and I submitted, test/spec/rails now offers some handy new specs for testing your routes.

assert_generates => should.route_to

Where you’d use #assert_generates in traditional Rails + test/unit, test/spec/rails now supports #route_to as a more spec-flavored alternative. For example, to verify that a given set of URL options routes to the expected path…

assert_generates "/users/1", :controller => "users", :action => "show", :id  => "1"

becomes

{:controller => "users", :action => "show", :id  => "1"}.should.route_to "/users/1"

assert_recognizes => should.route_from

And where our ancestors once used #assert_recognizes, test/spec/rails now offers #you_bettuh_recognize #route_from. “An example would be nice”, you say? Well, to perform essentially the inverse of the above test…

assert_recognizes({:controller => "users", :action => "show", :id => "1"}, {:path => "/users/1", :method => :get})

becomes

{:path => "/users/1", :method => :get}.should.route_from :controller => "users", :action => "show", :id =>"1"

The rdoc offers additional examples, and check out the test/spec/rails README for more mappings from old-school test/unit assertions to test/spec/rails equivalents.