How to test user routes in the controller using rspec

I determined my route in the routes.

get "packages/city/:location_id", to: "packages#index" 

In controller_spec.rb ,

 get :index 

gives this error

 ActionController::UrlGenerationError: No route matches {:action=>"index", :controller=>"packages"} 

How to explicitly specify user routes in the controller specification?

+7
source share
4 answers

Perhaps this will help if you declare your route this way?

 get "packages/city/:location_id" => "packages#index" 

Remember to specify the location_id parameter in the specs, for example. get :index, location_id: 1 .

+11
source

2017

I tried the solutions above, but they did not work. I got:

 ArgumentError: unknown keyword: location_id 

It seems RSpec now requires the params parameter. The corresponding call will look like this:

 get(:index, params: { location_id: 123 }) 
+7
source

because you do not pass location_id

the route is defined as follows:

/packages/city/:location_id

so to do it you need to do something like

get :index, location_id: 1234

Had the same problem with the controller specification:

 # rake routes | grep media_order teacher_work_media_orders PATCH /teacher/works/:work_id/media_orders(.:format) teacher/media_orders#update 

when i did this:

 # spec/controller/teacher/media_orders_controller patch :update data: {} 

I got

  Failure/Error: patch :update ActionController::UrlGenerationError: No route matches {:action=>"update", :controller=>"teacher/media_orders"} 

but when i did

 patch :update, work_id: 1234, data: {} 

who worked

+2
source

2019

Solved the same error on my controller specification. I tried to make and verify decisions, but they also did not work, either did not lead to a method error, or saved a route matching error.

Direct determination of the route, as in the decision made, also did not satisfy the errors.

After a long search and some keyboard tests, the tests pass.

What is worth noting

  • controller for polymorphic resource
  • routes are nested in resources :location, only[:index, :show] do... end
  • these are API routes, so only JSON

Decision

 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 

Thus, in the end, it was a combination of both solutions, but I had to put them in a parameter hash, otherwise it threw out the name / absence of the method or route error.

Conclusion

  • association links must be in the params hash
  • even if the controller responds to: json, it will not generate errors, there are no route errors
  • you must include a data hash in the request, otherwise route matching errors will not be displayed

Hope this helps,

Hurrah!

-1
source

Source: https://habr.com/ru/post/1216162/


All Articles