RSpec routing test problems with params in nested resources

nested-resources, param, rspec, ruby, ruby-on-rails

Solution

Routing specs should test that the action (`get`) given a path as a string (i.e. "/first/1/second/2") will route to an action with the correct parameters set (i.e. `first_id: 1, id: 2`)

You don't need to create an instance of your models here. It's unnecessary and it'll just slow down the spec.

describe MenusController do
  describe 'routing' do
    it 'routes to #index' do
      get('/restaurants/42/menus').should route_to('menus#index', restaurant_id: 42)
    end

    it 'routes to #show' do
      get('/restaurants/42/menus/37').should route_to('menus#index', restaurant_id: 42, id: 37)
    end
  end
end

You can also pass in other arguments, like `format: :json`, or anything else that might be gleaned from a URL string, as it's mainly testing that your routes file directs you to the correct place with the correct parameters.

Problem

i have a strange problem.. rspec generated a class named menus_routing_spec.rb in spec/routing the tests are failing because menus is a nested resource of restaurant. this is my test: ``` describe MenusController do before :each do @restaurant = FactoryGirl.create(:random_restaurant) @menu = FactoryGirl.create(:menu) end describe 'routing' do it 'routes to #index' do params = {} params['restaurant_id'] = @restaurant #get('/restaurants/:restaurant_id/menus').should route_to('menus#index') #get(restaurant_menus_path(@restaurant)).should route_to('menus#index') #get(restaurant_menus_path, { :restaurant_id => @restaurant }).should route_to('menus#index') get restaurant_menus_path, { :restaurant_id => @restaurant.to_param } expect(response).should route_to('menus#index') end ``` the path in rake routing looks like this: ``` restaurant_menus_path GET (/:locale)/restaurants/:restaurant_id/menus(.:format) menus#index ``` i get always this error message: ``` Failure/Error: get restaurant_menus_path, @restaurant.to_param ActionController::UrlGenerationError: No route matches {:action=>"index", :controller=>"menus"} missing required keys: [:restaurant_id] ``` I tried also the other ones.. but same error.. does anyone can see where i am doing the mistake? this is a test in spec/controllers/menus_controller_spec.rb which works fine ``` it 'renders the index template' do get :index, { :restaurant_id => @restaurant } expect(response).to render_template('index') end ``` thank you very much for help

Original source