Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test custom routes in controller with rspec

I have defined a custom route in routes.rb

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 the custom routes in controller specs?

like image 774
Oatmeal Avatar asked Mar 26 '15 08:03

Oatmeal


People also ask

How do I test an RSpec file?

To run a single Rspec test file, you can do: rspec spec/models/your_spec. rb to run the tests in the your_spec. rb file.

What RSpec method is used to create an example?

The describe Keyword The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.


1 Answers

2019

Was tackling this same error on my controller specs. Tried accepted and follow up solutions, but they also did not work, either led to no method error or persisted the no route match error.

Directly defining the route like in the accepted solution also did not satisfy the errors.

After much searching and some keyboard smashing tests pass.

Things to note

  • controller is for polymorphic resource
  • routes are nested within the resources :location, only[:index, :show] do ... end
  • this is API routes, so JSON only

Solution

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

So in the end it was a combination of both solutions, but had to put them in the params hash or else it would throw name/no method or route errors

Conclusion

  • references to the association must be in the params hash
  • even if controller responds_to :json, it will throw errors no route errors
  • must include a data hash in your request or no route match errors will appear

Hope this helps,

Cheers!

like image 86
Denis S Dujota Avatar answered Oct 01 '22 17:10

Denis S Dujota