# Specing the Precedence of Rails Routes

**URL:** <https://www.ruby-forum.com/t/specing-the-precedence-of-rails-routes/149010>\
**Category:** RSpec\
**Created:** [September 19, 2008, 10:38am UTC](https://www.ruby-forum.com/t/specing-the-precedence-of-rails-routes/149010 "2008-09-19T10:38:56Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mwalsh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/91b2a8/32.png) [@mwalsh](https://www.ruby-forum.com/u/mwalsh)\
**Post date:** [September 19, 2008, 10:38am UTC](https://www.ruby-forum.com/t/specing-the-precedence-of-rails-routes/149010/1 "2008-09-19T10:38:56Z")

</div>

Sorry that this is only a tentatively RSpec-related question folks.

I had a bug today which was caused by two routing resources being  
specified in a particular order:

map.resources :comments  
map.resources :posts, :has\_many =\> :comments

When I was in the CommentsController, rendering the index action for  
a particular post, I made a link to sort the comments like this:

\<%= link\_to ‘Sort by date’, :sort =\> “date” %\>

The idea is that this will then render a link like  
/posts/123/comments?sort=date

However, I actually got this:  
/comments?sort=date

It seems that the order of the routing is important here: if I flip  
order of the map.resources calls so that the posts one comes first,  
the link renders as expected.

So I concluded that the bug is caused by the routing code matching  
the first suitable route that it heard about.

My question is about how to reproduce this in a spec.

If I write this:  
route\_for(:controller =\> ‘comments’, :post\_id =\> ‘123’, :sort  
=\> ‘date’).should == “/posts/123/comments/?sort=date”

The spec passes. So something different is happening when my view is  
rendered, I guess to do with the way the controller and post\_id are  
implied from the params when I call link\_to.

I can, and will, tighten up the view spec. But any thoughts on how to  
spec the routing specifically so that someone can’t re-order these  
map.resources calls and break things?

## cheers, Matt

[http://blog.mattwynne.net](http://blog.mattwynne.net)

> **[Find the Best Concerts Near You, Tour Dates & Tickets Worldwide | Songkick](https://www.songkick.com/)**
>
> Find live music near you, track your favorite artists, get instant concert alerts and buy tickets for all the best upcoming concerts.

In case you wondered: The opinions expressed in this email are my own  
and do not necessarily reflect the views of any former, current or  
future employers of mine.
