RSpec and devise : cannot sign_in admin

deviserspec

I am migrating my standart Rails unit tests to RSpec and i have problems with devise. All controller containing devise authentication are failing with RSpec.

I try to sign_in an admin in RSpec following the devise tutorial, without success :

https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-(and-rspec)

Here is what i tried :

/spec/controllers/ipad_tech_infos_controller_spec.rb

before :each do
    @request.env["devise.mapping"] = Devise.mappings[:admin]
    @admin = FactoryGirl.create :admin
    sign_in @admin
end

/spec/support/devise.rb

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

/spec/factories/admin.rb

FactoryGirl.define do
  factory :admin do
    email "abc@abc.com"
    password "foobar"
    password_confirmation {|u| u.password}
  end
end

My model is not confirmable, all my controller spec are failing.

If i remove before_filter :authenticate_admin! then all my tests pass.

Can anybody help ?

Best Answer

Likely culprit: Make sure you're not setting the session explicitly in your controller specs.

For instance, if you're using the default Rspec scaffold generator, the generated controller specs pass along session parameters.

get :index, {}, valid_session

These are overwriting the session variables that Devise's helpers set to sign in with Warden. The simplest solution is to remove them:

get :index, {}

Alternatively, you could set the Warden session information in them manually, instead of using Devise's helpers.

Related Topic