[rspec-users] Tests that require a logged in user / session cookie

Justin Ko jko170 at gmail.com
Wed Aug 24 21:40:49 EDT 2011


On Wed, Aug 24, 2011 at 6:40 PM, Matthias Siegel
<matthiassiegel at gmail.com>wrote:

> Hi,
>
> I'm fairly new to RSpec with Rails and I'm trying to work out how I can
> write request specs for resources that require a logged in user.
>
> I can't get this one to pass:
>
>
> describe "GET /admin/account" do
>
>  it "should have a 200 status code when logged in" do
>    post "/login", { :email => @user.email, :password => @user.password }
>    response.should redirect_to("/admin")
>    response.code.should eq("302")
>    get "/admin/account"
>    response.code.should eq("200")
>  end
>
> end
>
>
> The login post part works fine and the session gets created correctly in
> the login method, but then the test fails at 'get "/admin/account"' because
> the session suddenly is empty.
>
> I have tried another approach where I set the session manually, to simulate
> a logged in user:
>
>
> describe "GET /admin/account" do
>
>  it "should have a 200 status code when logged in" do
>    session[:user_id] ||= @user.id
>    get "/admin/account"
>    response.code.should eq("200")
>  end
>
> end
>
>
> But again the session arrives empty in my authorisation method when trying
> 'get "/admin/account"'.
>
> My guess is that it fails because the session relies on cookies and in test
> mode there obviously is no browser and no cookie.
> Are there ways to simulate a logged in user in an app that creates sessions
> with cookies?
>
> Thanks for any suggestions
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>


What you are doing *should* work. Are there any before_filters altering the
session? Maybe a gem doing it? Maybe you have an admin namespace that
calls/uses a different session?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20110824/fb133a70/attachment.html>


More information about the rspec-users mailing list