Ala*_*ain 5 controller rspec routes ruby-on-rails
我有这条路线:
resources :items, path: 'feed', only: [:index], defaults: { variant: :feed }
Run Code Online (Sandbox Code Playgroud)
它嵌套在api和v1名称空间中.(request_source参数来自Api命名空间).
我想在我的控制器规范中测试索引操作.我试过了:
get :feed, community_id: community.id, :request_source=>"api"
Run Code Online (Sandbox Code Playgroud)
不起作用,也是如此:
get :index, community_id: community.id, :request_source=>"api", variant: 'feed'
Run Code Online (Sandbox Code Playgroud)
他说:
ActionController::RoutingError:
No route matches {:community_id=>"14", :request_source=>"api", :variant=>"feed", :controller=>"api/v1/items"}
Run Code Online (Sandbox Code Playgroud)
- - - -编辑 - - - - -
我想使用变量将参数发送到控制器的原因是因为我有所有这些路径:
resources :items, path: 'feed', only: [:index], defaults: { variant: 'feed' }
resources :items, path: 'popular', only: [:index], defaults: { variant: 'popular' }
Run Code Online (Sandbox Code Playgroud)
然后,在ItemsController中,我有一个前置过滤器"get_items"用于索引操作:
def get_items
if params[:variant] == 'feed'
....
elsif params[:variant] == 'popular'
....
end
Run Code Online (Sandbox Code Playgroud)
看来问题出在定义上defaults: { variant: :feed }。您能否详细说明一下您试图用它来完成什么?
我创建了一个应用程序来测试您所拥有的内容,并在其中包含以下内容config/routes.rb
namespace :api do
namespace :v1 do
resources :items, path: 'feed', only: :index
end
end
Run Code Online (Sandbox Code Playgroud)
我跑步时得到了这个rake routes。
$ rake routes
api_v1_items GET /api/v1/feed(.:format) api/v1/items#index
Run Code Online (Sandbox Code Playgroud)
更新:params为您可以在操作中使用的路线中未定义的变量设置默认值。
params[:variant] ||= 'feed'
Run Code Online (Sandbox Code Playgroud)
更新 2:params[:variant]您可以像这样有条件地在 before 过滤器中分配。
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
768 次 |
| 最近记录: |