Based on my understanding of the rspec spec, I would expect the following example to pass.
describe ApplicationController do
controller do
def test
end
end
it "calls actions" do
get :test
end
end
Instead it fails with:
No route matches {:controller=>"anonymous", :action=>"test"}
I've even tried defining the route for the "anonymous" controller in the routes file but to no avail. Is there something I'm missing here? This should work, shouldn't it?
In order to use custom routes within an anonymous controller spec you need to amend the route set in a before block. RSpec already sets up the RESTful routes using resources :anonymous
in a before block, and restores the original routes in an after block. So to get your own routes just call draw on @routes
and add what you need.
Here's an example from an ApplicationController
spec that tests the rescue_from CanCan::AccessDenied
require 'spec_helper'
describe ApplicationController
controller do
def access_denied
raise CanCan::AccessDenied
end
end
before do
@routes.draw do
get '/anonymous/access_denied'
end
end
it 'redirects to the root when access is denied' do
get :access_denied
response.should redirect_to root_path
end
it 'sets a flash alert when access is denied' do
get :access_denied
flash.alert.should =~ /not authorized/i
end
end
Update
Handling for this has been improved somewhere around RSpec 2.12. If your using > 2.12 then you no longer need to hook into @routes
.
Draw custom routes for anonymous controllers
I was having a similar problem. In my case the solution was including an :id parameter in the get request in the test.
I.e.
get :test, :id => 1
Check your routes and see if you are missing a certain parameter (probably :id), then add that to the test.
It seems that rspec gives you a set of RESTful routes to use. Thus if you only use standard action names in your anonymous controller, you won't get this problem. To date I've never had a reason to use anything other than 'index'.
describe ApplicationController do
describe 'respond_with_foo' do
controller do
def index
respond_with_foo
end
end
it 'should respond with foo' do
get :index
response.should be_foo
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With