0fha9w
Last Updated: February 25, 2016
·
3.725K
· edelpero
375b7e3e6b2365fdd0f127f4e224f4dc

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!

end

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
    end
  end

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

    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
      end
    end
  end

end

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.

Say Thanks
Respond

1 Response
Add your response

14227
10083d566019d1ec9fb39e060850274e

Thanks, Helped me out today!

over 1 year ago ·
Awesome Job

E20ce6a2 ca1f 11e7 82be 7f617c8310c9
SENIOR DEVELOPER (m/w)
·
Berlin, Köln, Hamburg, München
·
Full Time