Search code examples
ruby-on-railsrspecroutesrspec-rails

Passing 2 objects to a named route in RSpec


In my RSpec test I do: delete recurring_events_path(@group, @recurring_event), but that yields DELETE "/groups/705777939/recurring_events.496

How should I craft the arguments to recurring_events_path so that it yields /groups/705777939/recurring_events/496?

routes.rb

 45   resources :groups, except: %i[new edit]
 [snipp..]
 56   scope "groups/:group_id" do
 57     resources :posts, except: %i[new edit]
 58     put "posts/:id/pin", to: "posts#pin"
 59
 60     resources :recurring_events, except: %i[show]
 61     get "recurring_events/upcoming" => "recurring_events#upcoming", as: :upcoming
 62     get "recurring_events/past" => "recurring_events#past", as: :past
 63
 64     scope "/posts/:post_id" do
 65       resources :comments, except: %i[new edit]
 66     end
 67   end

$ rake routes

recurring_events GET    /groups/:group_id/recurring_events(.:format)            recurring_events#index
                 POST   /groups/:group_id/recurring_events(.:format)            recurring_events#create
                 PATCH  /groups/:group_id/recurring_events/:id(.:format)        recurring_events#update
                 PUT    /groups/:group_id/recurring_events/:id(.:format)        recurring_events#update
                 DELETE /groups/:group_id/recurring_events/:id(.:format)        recurring_events#destroy

Solution

  • Change your route to use nested resources like this:

     resources :groups, except: %i[new edit]
       resources :posts, except: %i[new edit]
         resources :comments, except: %i[new edit] #be careful with this, tree levels of nesting is not recommended, I would move this out of the "group" namespace
         member do
           put :pin
         end
       end
    
       resources :recurring_events, except: %i[show] do
         collection do
           get :upcoming
           get :past
         end
       end
     end
    

    Now rake routes should give you all routes with it's names.

    More info on the docs: https://guides.rubyonrails.org/routing.html#nested-resources