[英]How to test custom routes in controller with rspec
我在routes.rb中定義了一個自定義路由
get "packages/city/:location_id", to: "packages#index"
在controller_spec.rb
,
get :index
給出了這個錯誤,
ActionController::UrlGenerationError:
No route matches {:action=>"index", :controller=>"packages"}
如何在控制器規范中明確指定自定義路由?
如果您宣布這樣的路線,也許會有所幫助?
get "packages/city/:location_id" => "packages#index"
請記住在規范中提供location_id
參數,例如get :index, location_id: 1
。
我嘗試了上面的解決方案,但他們沒有工作。 我有:
ArgumentError:
unknown keyword: location_id
似乎RSpec現在需要一個params
參數。 相應的調用如下所示:
get(:index, params: { location_id: 123 })
這是因為你沒有傳遞location_id
路線定義為匹配:
/packages/city/:location_id
所以為了遵守它,你需要做類似的事情
get :index, location_id: 1234
與Controller規范有相同的問題:
# rake routes | grep media_order
teacher_work_media_orders PATCH /teacher/works/:work_id/media_orders(.:format) teacher/media_orders#update
當我做的時候:
# spec/controller/teacher/media_orders_controller
patch :update data: {}
我有
Failure/Error: patch :update
ActionController::UrlGenerationError:
No route matches {:action=>"update", :controller=>"teacher/media_orders"}
但是當我這樣做的時候
patch :update, work_id: 1234, data: {}
有效
在我的控制器規格上解決了同樣的錯誤。 嘗試接受和跟進解決方案,但他們也沒有工作,或導致沒有方法錯誤或持續無路由匹配錯誤。
直接定義路徑就像在接受的解決方案中一樣也不能滿足錯誤。
經過多次搜索和一些鍵盤粉碎測試通過。
resources :location, only[:index, :show] do ... end
let(:location) do
create(:location)
end
shared_examples("a user who can't manage locations") do
describe 'GET #index' do
it 'denies access' do
get :index, params:{location_id: location.locationable.id, format: :json}
expect(response).to have_http_status :unauthorized
end
end
end
所以最后它是兩個解決方案的組合,但不得不將它們放在params散列中,否則它會拋出名稱/沒有方法或路由錯誤
希望這可以幫助,
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.