将 2 个对象传递到 RSpec 中的命名路由

Passing 2 objects to a named route in RSpec

在我的 RSpec 测试中我做了: delete recurring_events_path(@group, @recurring_event),但这会产生 DELETE "/groups/705777939/recurring_events.496

我应该如何设计 recurring_events_path 的参数以使其产生 /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

$ 佣金路线

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

recurring_events_path这里代表你的#index路线

如果您在路线中使用 resource,则路径应为 destroy_recurring_events_path。否则,您需要在路由声明中指定 as: 选项。喜欢as: :destroy_recurring_events

您可以使用 rake routes 命令查看路由的别名

更改您的路由以使用嵌套资源,如下所示:

 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

现在 rake routes 应该给你所有的路由名称。

有关文档的更多信息:https://guides.rubyonrails.org/routing.html#nested-resources

您只需要使用 recurring_event_path 作为单一事件而不是 recurring_events_path