RSpec "No route matches" error but they match - ruby-on-rails

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.

Related

Rspec tests not finding matching routes

I'm getting unexpected errors when running some Rspec tests. They are
1) PeopleController redirects when loading root should redirect to the splash page
Failure/Error: get '/'
ActionController::UrlGenerationError:
No route matches {:action=>"/", :controller=>"people"}
...
2) PeopleController redirects when loading /people/show should redirect to the base person path
Failure/Error: get '/show' #/show
ActionController::UrlGenerationError:
No route matches {:action=>"/show", :controller=>"people"}
I don't understand why Rspec can't find the routes.
From the controller, people_controller.rb:
class PeopleController < ApplicationController
...
def show
redirect_to people_path
end
def index
#people = Person.all
end
...
From the Rspec file people_controller_spec.rb:
describe PeopleController do
describe "redirects" do
context "when loading root" do
it "should redirect to the temp page" do
get '/'
last_response.should be_redirect
follow_redirect!
last_request.url.should include('/temp')
end
end
context "when loading /people/show" do
it "should redirect to the base people path" do
get '/people/show'
last_response.should be_redirect
follow_redirect!
last_request.url.should include('/people')
end
end
end
end
And my routes:
$ rake routes
Prefix Verb URI Pattern Controller#Action
...
person GET /people/:id(.:format) people#show
...
root GET / redirect(301, /temp)
routes.rb:
Rails.application.routes.draw do
resources :temp
resources :people
# map '/' to be a redirect to '/temp'
root :to => redirect('/temp')
end
What am I missing to get the routes from test to match up? I could see the root test not working because it's not technically handled by the People controller (I tried putting it in as a sanity test and only made myself more confused) but the /show failure really makes no sense to me.
Inside a controller test the method get takes an action argument, not a path. If the resource is a member (as opposed to a collection), you must also specify the id parameter, so:
get :show, id: 1
will call the #show action on an instance of PeopleController, with a params hash including {id: '1'}.
This is described in more detail in the Guide to Testing Rails Applications.

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?
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!

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

Rspec integration test: Routes not available

I was trying to write an integration test testing, if my controller raises a ActiveRecord::RecordNotFound exeption for deleted articles (which are just marked as deleted):
it "should return 404 for deleted articles" do
#article = Factory :article, :status => "deleted"
expect { get edit_article_path(:id => #article.id) }.to raise_error(ActiveRecord::RecordNotFound)
end
These kind of tests work fine in a controller spec, but inside of the spec/requests I get this error:
expected ActiveRecord::RecordNotFound, got #<ActionController::RoutingError: No route matches {:action=>"edit", :controller=>"articles", :id=>595}>
So it looks up my routes correctly (since it knows the controller etc.) but still raises the error. Why is that?
Thanks, Johannes
If this test is in your spec/controllers directory, then the get method you're calling isn't expecting a path, it's expecting a symbol for the controller action you want to call. So you'd need to change the expect line to something like:
expect { get :edit, :id => #article.id }.to raise_error(ActiveRecord::RecordNotFound)
Take a look at the RSpec Controller Spec documentation for more info.

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