jump to navigation

Rails and rspec (and machinist) – testing authentication-blocked controllers June 16, 2011

Posted by ficial in rspec testing, ruby on rails, techy.

I’ve been working on a rails app that has an admin section that requires log in to access. I’m using a very simple system, driven by omniauth. The details of the auth process aren’t relevant here. The key part is that I have:

  before_filter :require_login
  def require_login
    @current_user ||= User.find_by_id(session[:user_id])
    redirect_to admin_login_path unless @current_user

at the start of the admin controllers (actually at the start of a general admin controller from which the specific admin controllers inherit). When I first put this in place all my tests of the admin controllers were failing, because there wasn’t a logged in user.

To simulate a logged in user I created a simple method in my spec_helper file

def logged_in
  @current_user = User.make!
  session[:user_id] = @current_user.id

then I call that method for any test that requires a logged in user. E.g.

describe Admin::ThingsController do
  before(:each) do    
    # uncomment the line below to be logged in for every test in this controller
    # logged_in

  describe "GET index", :focus => true do
    it "assigns all things as @things if logged in" do
      tlist = Thing.make!(2)      
      get :index
      assigns(:things).should == tlist
    it "redirects to the log in screen if not logged in" do
      get :index
      response.should redirect_to(admin_login_path)


I’ve also found it useful to have

def logged_out
  @current_user = nil
  session[:user_id] = nil

which lets me put logged_in in my before(:each) block and then log out only for the specific tests (usually a re-direct test) for the case of a user not logged in.



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: