Topic: Rspec and Session signin tokens

Basically I'm trying to figure out how to simulate a signed-in user in rspec.

My authentication system uses a "session[:user] = user.id" type of authentication. If you are familiar with Hartl's tutorial, I'm (loosely) working through it but using the Rails session token instead of the permanent cookie token.

I'm now trying to test a PUT to a create action that should only be accessible to the correct logged-in user (Section 9.2.2 of Hartl's Rails 3.2.3 Tutorial), but based on the errors I'm getting, it seems that the "sessions" method is not accessible using rspec.

My rspec code looks like this:

spec/requests/authentication_pages_spec.rb (this code seems to work ok):

   describe "as wrong user" do
      let(:user) { FactoryGirl.create(:user) }
      let(:wrong_user) { FactoryGirl.create(:user, email: "wrong@example.com") }
      before { sign_in user }    # where sign_in is defined in the helper below
     ....

      describe "submitting a PUT request to the Users#update action" do
        before { put user_path(wrong_user) }
        specify { response.should redirect_to(root_path) }
      end
   end

spec/support/utilities.rb (the problem lies herein):

  def sign_in(user)
    # Capybara sign-in
    visit signin_path
    fill_in "Email",    with: user.email
    fill_in "Password", with: user.password
    click_button "Sign in"

    # Sign in when not using Capybara
    session[:remember_token] = user.id  # <---Problem code
  end

When I run the rspec, I get this error each time the sign-in action is called:

Failure/Error: sign_in user
     NoMethodError:
       undefined method `session' for #<User:0xa7c3ecc>
     # ./spec/support/utilities.rb:17:in `sign_in'
     # ./spec/requests/user_pages_spec.rb:78:in `block (3 levels) in <top (required)>'

So where am I going wrong? What is the proper way to simulate a logged in user for a Rails session authentication system?

Thanks.

Last edited by Brian71 (2012-04-13 20:02:42)

Re: Rspec and Session signin tokens

Well, not long after posting that, I found a solution on StackOverflow here:
http://stackoverflow.com/questions/5787 … quest-spec

For future reference, here's the fix:

I changed spec/support/utilities.rb to this:

def sign_in(user)
  # Capybara sign-in
  visit signin_path
  fill_in "Email",    with: user.email
  fill_in "Password", with: user.password
  click_button "Sign in"

  # Sign in when not using Capybara
  post sessions_path, :email => "foo@bar.com", :password => "password", :password_confirmation => "password"   # <-- code that worked
end