Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No route matches rspec's anonymous controller

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?

like image 373
Lachlan Cotter Avatar asked Aug 11 '11 14:08

Lachlan Cotter


3 Answers

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

like image 193
Cluster Avatar answered Oct 29 '22 17:10

Cluster


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.

like image 21
Tim O Avatar answered Oct 29 '22 16:10

Tim O


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
like image 5
Will Tomlins Avatar answered Oct 29 '22 15:10

Will Tomlins