I have the following in my Rails 3 controllers/application.rb (which I'm trying to write a spec for):
rescue_from CanCan::AccessDenied do |exception|
flash[:alert] = t(:access_denied)
if (current_user) then
redirect_to root_url
else
session[:direct_redirect] = request.url
redirect_to new_user_session_url
end
end
I'd like to write some specs to ensure the functionality works. I've placed the tests in spec/controller/application_controller_spec.rb, and figure I should write something such as:
it "should redirect to the root url" do
controller.stub(:authorize!) { raise CanCan::AccessDenied }
get :index
response.should redirect_to(root_url)
end
The problem is that get :index line. The spec throws back a 'no route matches controller => application" error. "Fair enough", I figured, and tried to route to a different controller. Attempts were:
* get :controller => 'purchases', :action => :index
* get purchases_url
* get '/purchases/'
All of which where interpreted as an action under the 'application' controller.
So, how can I route to a controller in rspec apart from the one in which the spec is written?
To test that kind of thing you're going to want to use anonymous controllers within RSpec. Relish has a fantastic example here about them.
Be sure to have a look around in other parts of that documentation too. I've learned a lot by just going through the examples they have there.
In your spec:
@controller = ADifferentController.new
expect(@controller).to receive(:this_other_thing)
get :index # or whatever
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