Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No route match in controller spec for my complex route

I have this route:

resources :items, path: 'feed', only: [:index], defaults: { variant: :feed }

which is nested in the api and v1 namespaces. (the request_source params comes from the Api namespace).

I want to test the index action in my controller spec. I tried:

get :feed, community_id: community.id, :request_source=>"api"

does not work, and so does:

get :index, community_id: community.id, :request_source=>"api", variant: 'feed'

saying:

ActionController::RoutingError:
   No route matches {:community_id=>"14", :request_source=>"api", :variant=>"feed", :controller=>"api/v1/items"}

-------EDIT---------

The reason why I want to use the variant to send the params to the controller is because I have all these routes:

    resources :items, path: 'feed',    only: [:index], defaults: { variant: 'feed' }
    resources :items, path: 'popular', only: [:index], defaults: { variant: 'popular' }

Then, in ItemsController, I have a before filter "get_items" for the index action wich does:

def get_items
  if params[:variant] == 'feed'
     ....
elsif params[:variant] == 'popular'
    ....
end
like image 415
Alain Avatar asked Nov 04 '22 17:11

Alain


1 Answers

It looks like the problem is coming from defining defaults: { variant: :feed }. Could you please elaborate what you are attempting to accomplish with that.

I created an application to test what you have and with the following in config/routes.rb

namespace :api do
  namespace :v1 do
    resources :items, path: 'feed', only: :index
  end
end

I got this when I ran rake routes.

$ rake routes
api_v1_items GET /api/v1/feed(.:format) api/v1/items#index

Update: to set a default for the params variable for something that isn't defined in the route you can use in your action.

params[:variant] ||= 'feed'

Update 2: you can conditionally assign params[:variant] in a before filter like so.

class ItemsController < ApplicationController
  before_filter :get_variant

  # or more simply
  # before_filter lambda { params[:variant] ||= 'feed' }

  def index
    render text: params[:variant]
  end

private      

  def get_variant
    # make sure we have a default variant set
    params[:variant] ||= 'feed'
  end
end
like image 111
Baylor Rae' Avatar answered Nov 09 '22 02:11

Baylor Rae'