[rspec-users] mimicking a logged in user

Justin Ko jko170 at gmail.com
Sat Mar 3 22:21:49 UTC 2012


On Mar 3, 2012, at 12:35 PM, S Ahmed wrote:

> I'm testing my controller, and confirming that a logged-in user can view the page.
> 
> I have a session_helper that does this:
> 
> def signed_in?
>     !current_user.nil?
> end
> 
> And the current_user is set with:
> 
> def user_from_remember_token
>     remember_token = cookies[:remember_token]
>     User.find_by_remember_token(remember_token) unless remember_token.nil?
> end
> 
> 
> So in my controller, I need to fake a login somehow, how should I go about doing this?
> 
> I'm not sure if this is the best place for it, but so far what I tried was creating a method in my spec_helper's config block:
> 
> def test_sign_in(user)
>    controller.sign_in(user)
> end
> 
> (I get my user object from factorygirl).
> 
> So my controller_spec looks like:
> 
> 
> describe "index" do
>     before(:each) do
>       @user = Factory(:user)
>       test_sign_in(@user)
>     end
>     
>     it "should be successful" do
>       get 'index'
>       controller.current_user.should == @user
>       response.should be_success
>     end
>   end
> 
> 
> It is failing with current_user being nil.
> 
> Should I just somehow stub the call to 'user_from_remember_token' to return the factorygirl user?
> How can I do this?
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

Just set the :remember_token cookie:

https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/cookies


More information about the rspec-users mailing list