【问题标题】:Passing 2 objects to a named route in RSpec将 2 个对象传递给 RSpec 中的命名路由
【发布时间】:2018-11-28 13:21:52
【问题描述】:

在我的 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

$ rake 路线

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

【问题讨论】:

  • 显示您的 routes.rb,您似乎没有从您的 rake routes 输出中正确设置路由(没有路由名称)

标签: ruby-on-rails rspec routes rspec-rails


【解决方案1】:

更改您的路线以使用这样的嵌套资源:

 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

【讨论】:

    【解决方案2】:

    recurring_events_path 这里代表你的#index 路由

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

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

    【讨论】:

    • 我已将rake routes 的recurring_evnts 部分添加到我的帖子中。只要您提供正确的 HTTP 动词,** recurring_events_path** 是否适用于所有列出的函数?
    • @martins,只有当 URL 相同时才有效,它适用于 /groups/:group_id/recurring_events GET 和 POST,但 PATCH、PUT 和 DELETE 的其他 URL 不同
    【解决方案3】:

    您只需将recurring_event_path 用作单数事件而不是recurring_events_path

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-15
      • 2019-12-07
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多