5
votes

I'm trying to start a new user session by creating a helper that POSTs a new user session. Here is what I have

def login(user)
  post user_session_path, :login => user.username, :password => user.password
end

And for user

user = Factory.create(:user)

I have a test in RSpec that directs the user to a page that requires authentication. Using the helper, I expect a new user session to be created. However, running the spec, it is telling me the current page is the login screen. This tells a new user session isn't being created and the user is being redirected to the login screen when accessing the restricted resource with no user session. Looking at the test logs, this is the case.

Also looking at the logs, it is saying the POST action is unauthorized.

Started POST "/login" for 127.0.0.1 at 2012-02-04 13:34:59 -0800
Processing by SessionsController#create as HTML
Parameters: {"login"=>"foo12", "password"=>"[FILTERED]"}
Completed 401 Unauthorized in 1ms
Processing by SessionsController#new as HTML
Parameters: {"login"=>"foo12", "password"=>"[FILTERED]"}
Rendered devise/shared/_links.erb (1.4ms)
Completed 200 OK in 15ms (Views: 12.7ms | ActiveRecord: 0.0ms)

I tried manually using the login page through a browser and was able to create a session just fine. I've also wrote up a test with Capybara that visits the login page, fills in the user credentials, and submit. This creates a new user session with no problems.

1
I ran into this briefly, when I tried to combine these 2 declarations into 1, by mistake. They should be separate. config.before(:each) do DatabaseCleaner.strategy = :transaction end config.before(:each) do DatabaseCleaner.start end into ` config.before(:each) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.start end `Ryan

1 Answers

27
votes

I got this to work by including Warden::Test::Helpers (which devise uses behind the scenes)

require 'spec_helper'
include Warden::Test::Helpers

describe "...Whatever..." do

  before(:each) do
    @user = Factory.create(:user)
    login_as @user, :scope => :user
  end
  ...

found the solution from here: http://blog.joshmcarthur.com/2011/06/11/integration-tests-with-devise-and-rspec/