Warning: Creating default object from empty value in /homepages/39/d161420129/htdocs/p373.net/wp/wp-content/themes/p373b/admin/functions.php on line 183
Rails Nested Resource Controllers – what not to do when testing

Rails Nested Resource Controllers – what not to do when testing

Testing nested resource controllers is pretty easy and awesome.  It is not easy and awesome, however, if the name of your nested controller differs from the route you want to use.

Examine the following

resources :posts do
  resources :comments, controller: "UserComments"

Did you catch whats wrong with the above?  You may not actually run into any problems with the above code if you don’t do functional tests for your nested comments controller.

I had the following:

require 'spec_helper'

describe UserCommentsController do
  it "should create a comment" do
      expect {
        post :create, {:post_id => 1}
      }.to change(UserComment, :count).by(1)

which yielded the following error:

Failure/Error: post :create, {:post_id => 1}
       No route matches {:post_id=>"1", :controller=>"user_comments", :action=>"create"}

So weird, this is exactly how the requests looks when I access via a web browser, so what gives?  Well, after some excruciating digging into Rails route sets and route generation code, and finally bottoming out at some method called “non_recursive” which is actually where the meat of the route matching occurs, I finally realized the casing was wrong in my route set.  When specifying a controller, use underscore notation!

so for the love of buddha:

resources :posts do
  resources :comments, controller: "user_comments"

Why does the server match the route properly but not the tests! le sigh…

Oi, hope this helps someone else in the future, or me when it happens again…


    This entry was posted in Coding, Ruby/Rails, Technology. Bookmark the permalink. Both comments and trackbacks are currently closed.