How to test custom routes in controller with rspec - ruby-on-rails

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?

Perhaps it helps if you declare your route like this?
get "packages/city/:location_id" => "packages#index"
Remember to provide a location_id param in specs, e.g. get :index, location_id: 1.

2017
I tried the solutions above but they did not work. I got:
ArgumentError:
unknown keyword: location_id
It seems that RSpec now requires a params parameter. The corresponding call would look like this:
get(:index, params: { location_id: 123 })

it's because you are not passing location_id
the route is defined to match:
/packages/city/:location_id
so in order to comply with it you need to do something like
get :index, location_id: 1234
Had the same issue with Controller spec:
# rake routes | grep media_order
teacher_work_media_orders PATCH /teacher/works/:work_id/media_orders(.:format) teacher/media_orders#update
when I did:
# 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: {}
that worked

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!

Related

"resources :post, except: :new" makes Rails think the route /posts/new would point to a post ID "new"

I have the following route:
resources :success_criteria, except: :new
The following spec fails:
describe SuccessCriteriaController do
describe 'routing' do
it 'routes to #new' do
expect(get('/success_criteria/new')).to_not be_routable
end
end
end
Failure message:
Failure/Error: expect(get('/posts/new')).to_not be_routable
expected {:get=>"/posts/new"} not to be routable, but it routes to {:controller=>"posts", :action=>"show", :id=>"new"}
The controller looks like this:
class SuccessCriteriaController < InheritedResources::Base
load_and_authorize_resource
end
Why does Rails think that posts/new would point to a post with the ID new? That's not right, is it? Does it maybe have to do with InheritedResources?
I believe that if you don't add a constraint to your show route saying that it will only accept digits, everything you put after posts are mapped to be an id to that route.
That means that if your try to access posts/something it would probably throw an ActiveRecord error showing that it couldn't find the Post with id=something.
To add a constraint, add constraints like this:
resources :success_criteria, except: :new, constraints: { id: /\d+/ }

How to test that a route does not exist in Rails 4.x

If I have a route not defined, how do I test that it returns a 404?
Here is the relevant part of routes.rb
resources :reservations, only: [:index,:create,:destroy]
You can create, destroy and list reservations, but not change them.
The test then is:
patch :update, id: #reservation, reservation: { somefield: "data" }
assert_response :missing
This should pass, since the lack of a route should return a 404. Instead, I get a UrlGenerationError:
ActionController::UrlGenerationError: No route matches {:action=>"update", :controller=>"reservations", :id=>"980190962", :reservation=>{:somefield=>"data"}}
I get it; the patch call from the test cannot generate a URL. So how do I test that such a URL call would generate a 404?
You actually could assert an error like this has been thrown, would it be sufficient for you?
assert_raise ActionController::UrlGenerationError do
patch :update, id: #reservation, reservation: { somefield: "data" }
end

RSpec "No route matches" error but they match

I have tests like those:
RSpec.describe RestaursController, :type => :controller do
context "GET /restaurs/:id" do
before do
#rest = FactoryGirl.create :restaur
end
context "resource exists" do
subject { get "restaurs/#{#rest.id}"}
it { expect(subject).to render_template(:show) }
end
context "resource doesn't exists" do
subject { get "restaurs/#{#rest.id + 1}" }
it { expect(subject).to redirect_to(:root) }
end
end
end
When I run those tests RSpec says:
Failure/Error: subject { get "restaurs/#{#rest.id}"}
ActionController::UrlGenerationError:
No route matches {:action=>"restaurs/7", :controller=>"restaurs"}
But I think my routes are OK. Look on rake routes log
Prefix Verb URI Pattern Controller#Action
restaurs GET /restaurs(.:format) restaurs#index
POST /restaurs(.:format) restaurs#create
new_restaur GET /restaurs/new(.:format) restaurs#new
edit_restaur GET /restaurs/:id/edit(.:format) restaurs#edit
restaur GET /restaurs/:id(.:format) restaurs#show
PATCH /restaurs/:id(.:format) restaurs#update
PUT /restaurs/:id(.:format) restaurs#update
DELETE /restaurs/:id(.:format) restaurs#destroy
root GET / restaurs#index
Have you got any ideas? What is the problem? Maybe it is about RSpec syntax or something like that?
That isn't how you get actions in a controller test. The argument to get is the name of the action, not a routable path. Routing isn't involved in testing controllers, and neither is rake routes.
You're giving it the action name "restaurs/7", which obviously isn't the real name of a method on your controller. Instead, you should be using get :show to invoke the actual method "show" on your controller, and then passing a hash of parameters:
get :show, id: #rest.id + 1
Similarly, you would use get :index, not get "/", and you would use get :edit, id: ..., not get "/restaurs/#{...}/edit". It's the actual method your meant to test on your controller, not whether a route actually leads you to the correct method.
As a related aside, your opening context is out of place. You shouldn't be using GET /restaurs:/:id as a context. Routing isn't involved here. Just test the method names.

Rails "POST" member route responds to all request types

I'm trying to set up a member route for my 'foo' controller, which is named 'bar' such that it should ONLY respond to post requests. However, I notice that in my RSpec tests it responds to ALL request types (GET, POST, PUT, DELETE).
I was under the impression that defining the route as so, would restrict it such that it would only respond to POST requests:
resources :foo do
member do
post 'bar'
do
end
This seems further confirmed by the fact that when I run rake routes it ONLY shows the 'bar' route like so:
bar_foo POST /foo/:id/bar(.:format) {:action=>"bar", :controller=>"foo"}
However, from RSPEC, the following test fails (meaning the controller processes request successfully) for GET, PUT, & DELETE:
describe FooController do
describe "GET bar" do
it "should not be successful" do
foo = FactoryGirl.create(:foo)
get :bar, :id => foo.id
response.should_not be_ok
end
end
end
Am I missing something small here? How do I restrict my 'bar' member route to only respond to "post" requests.
EDIT:
This appears to be an issue with either RSpec 2.0 or ActionController::TestCase, because I get the following error when I try to hit /foo/:id/bar on my sever with anything but POST:
Routing Error
No route matches [GET] "/foo/1/bar"
From my own experience it appears that RSpec controller tests will not attempt to enforce routing behavior as long as the route exists. RSpec does provide route testing, specifically the be_routable matcher.
Given the following route.rb snippet:
post :foo, to: 'foo#create'
it appears
it "won't work as expected" do
get :foo
expect(response).to be_ok #=> pass
post :foo
expect(response).to be_ok #=> pass
end
will pass. Only when the route is missing entirely from route.rb will it fail.
The following will pass and can be used to perform the test we're interested in:
it "responds to only the proper HTTP verbs" do
expect(get: :foo).not_to be_routable #=> pass - Cannot GET 🙅‍♂️
expect(post: :foo).to be_routable #=> pass - POST works 🎉
end

How to get RSpec to call a singular route when testing controller?

Anyone know how to get RSpec to call a singular route when testing controller?
It can't find the route b/c it doesn't know to look for a singular controller so I need a way to specify it.
routes.rb
resource :settings_group, :path => "/settings/scheduling/"
settings_groups_controller_spec.rb
describe SettingsGroupsController do
describe "GET show" do
let(:describe_action) { get :show }
it "sets #settings_group" do
describe_action
assigns(:settings_group).should be_kind_of(SettingsGroup)
end
end
end
...
ActionController::RoutingError:
No route matches {:controller=>"settings_groups"}
Just out of curiosity, but why does settings_group_controller.rb have
describe SettingsGroupsController (with an s)
Shouldn't they match?

Resources