Lee Ourand

Testing Nested Resources In Rails 3

October 21 2010

I recently ran into some problems when trying to run my functional tests while using nested resources in the new Rails 3. My routing was setup for nested resources, Foo has many Bars.

resources :foos do
  resources :bars

I used a rather contrived test to get started.

test "that I can GET the index" do
  get :index
  assert_response :success

The first error that I received, when using this fairly basic test was:

NoMethodError: undefined method `recycle!` for #<Bar:0x1033f09e0>

This error is easily corrected by renaming the fixture instance variable youre likely declaring in your setup. In my case, the Bar resource name needed to be updated.

setup do
# @bar = bars(:one) Change to:
  @my_bar = bars(:one) 

ActionController has its own set of instance variables named after the controller. In the commented out case above, you are squashing Rails instance variable, which causes this error.

After correcting this issue, I was still having problems.

ActionController::RoutingError: No route matches {:controller=>"bar"}

This was another really basic fix that took me longer than I care to admit to resolve. To fix this, you simply need to fix your test case to provide the parent resource id.

test "that I can GET the index" do
  get :index, :foo_id => @my_foo.id
  assert_response :success

Note that youll also need to declare a @my_foo variable in your setup for this to work. Otherwise, you can just use any number to get the routing to work. Happy testing!