Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails/RSpec: 'get' to a different controller

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?

like image 727
PlankTon Avatar asked Oct 04 '11 04:10

PlankTon


2 Answers

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.

like image 161
Ryan Bigg Avatar answered Sep 29 '22 05:09

Ryan Bigg


In your spec:

@controller = ADifferentController.new
expect(@controller).to receive(:this_other_thing)
get :index # or whatever
like image 5
Daniel Prejean Avatar answered Sep 29 '22 04:09

Daniel Prejean