Rails and rspec (and machinist) – testing authentication-blocked controllers June 16, 2011
Posted by ficial in rspec testing, ruby on rails, techy.Tags: ruby rails rspec controller test authenticated
trackback
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 end
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 end
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 end describe "GET index", :focus => true do it "assigns all things as @things if logged in" do tlist = Thing.make!(2) logged_in get :index assigns(:things).should == tlist end it "redirects to the log in screen if not logged in" do get :index response.should redirect_to(admin_login_path) end end end
I’ve also found it useful to have
def logged_out @current_user = nil session[:user_id] = nil end
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.
Comments»
No comments yet — be the first.