[rspec-users] Stubbing authentication across multiple controllers

Jerry West jerry.west at ntlworld.com
Thu May 17 05:26:59 EDT 2007


You might consider stubbing your controllers at a higher level.  
Presumably session/create sets up something in the session which your 
other controllers check to see if you are logged in.  If you have your 
controllers call some method to make the check you can stub that; so far 
as they are concerned it will be as if your user had logged in, but you 
need not actually call SessionController.  For example:


or even

    controller.stub!(:login_before_acting).and_return(true)   # 
before_filter :login_before_acting

though you can't use that to spec the authorization code in your 
controller ('cos it will skip the call to #authorized? which 
#login_before_acting would normally make).

Leave your detailed spec as it is for SessionController, but abstract 
the functionality out - and stub it - for everyone else.  It's your 
choice as to where you place the stubs; personally I make the controller 
call the before_filter but return immediately by stubbing #logged_in?  
and #authorized? as above.  This means I can run specs to ensure my 
controllers do the right thing if the user is not logged in (the stub 
returns false) and/or is not authorized(*).  You may also need to stub 
methods to return the current_user (etc) as required.  Put them in 
helper methods as you are doing and use in setup/before blocks as 
required.  YMMV.

Best wishes,

(*) There's a whole other discussion about this - surely if I've spec'd 
my authentication code all I need do is check my controller includes the 
module and calls the filter... but somehow I like to see the individual 
specs run for all my controllers...There is NO One True Way in rspec, 
all approaches are equal, but some are more equal than others.  Now I'm 
rambling :-).

More information about the rspec-users mailing list