Dave Schweisguth in a Bottle

How many meanings of that can you think of?

Rails’ named routes considered helpful

leave a comment »

The current Rails best practice is to use RESTful routes. One nice thing about a RESTful route is that it comes with a name. Similarly, :member and :collection routes are automatically named. But sometimes you need a plain old arbitrary route, which you can then name or not as you wish. It may seem like overkill to give every route a name, especially if the route is referred to infrequently in templates. But there’s another place where you’re virtually guaranteed to need that named route again: in tests.

Suppose your application’s home page needs to link to an about page. As with any other feature, we write the spec first (here using Webrat):

describe RootController do
  describe '#index' do
    get :index
    response.should have_selector 'a', :href => root_about, :content => 'About'

Next, implement the view. Perhaps we started with this easy specification and this is the entire contents of index.html.erb:

<%= link_to 'About', root_about %>

Not only is this much nicer than :controller and :action, it relieves us of having to specify twice (once in the template and once in the spec) what the route is to. Duplication eliminated before we’ve even implemented the route! To finish the thought, here’s the actual route, in routes.rb:

get 'about' => 'root#about', :as => root_about

Not a surprising choice, but we might have chosen any URL we liked without redoing any of the work we’d already done, as long as we kept the name.

Of course this applies to all routes, RESTful or not, and it need not apply only to view specs. Use named routes anywhere in your tests that you might have written out the URL. Except in routing specs, of course.


Written by dschweisguth

May 11, 2011 at 08:36

Posted in Programming, Rails, Ruby, Testing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s