Rails/RSpec: ‘get’ to a different controller

rspecruby-on-rails-3

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?

Best Answer

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.

Related Topic