Last Updated: February 25, 2016
· edelpero

Testing Anonymous Controllers with RSpec

Lately I been working on a project in which I needed to test that in my whole admin cms it requires the admin to be authenticated. I was using devise to handle the authentication and if you already worked with devise you know that it's as simple as adding a beforefilter :authenticateadmin!.

As you imagine, adding that before_filter to every and each one of my admin's cms controllers it's a bummer and also it would be a bad idea. So I decided to create a Admins::BaseController wich inherit from ApplicationController.

class Admins::BaseController < ApplicationController

  before_filter :authenticate_admin!


So far it's a peace of cake. Now we want to test our new Admins::BaseController, and our spec should look something like this:

require 'spec_helper'

describe Admins::BaseController do

  controller(Admins::BaseController) do
    def index

  describe "#authenticate_admin!" do
    before(:each) do
      @admin = FactoryGirl.create(:admin)
      @request.env["devise.mapping"] = Devise.mappings[:admin]

    context "when admin is not logged in" do
      it "redirects admin to sign_in path" do
        get :index
        response.should redirect_to new_admin_session_path


Note that right after we've defined Admins::BaseController we make a call to the controller method and we pass as argument our controller. Inside the controller method we have to define the method we are going to test or use to test our base controller.

Another important thing is that if you are testing ApplicationController, you don't need to pass the name of the controller as an argument to the controller method.

You can find more information about this, here.

1 Response
Add your response

Thanks, Helped me out today!

over 1 year ago ·