Mocks does not work with RSpec and Devise

I am working on a Rails 3 web application currently with RSpec 2 and we use Devise for authentication. One (and soon many) of our controllers requires the user to log in. I know that Devise provides a sign_in test helper, but can it be used with RSpec or Mocha layout?

I originally tried @user = mock_model(User) , where the user is a Devise class. This will not work with sign_in :user, @user , since get 'index' will be redirected to the form of the sign.

Does anyone have experience testing with Devise and can help?

+3
source share
5 answers

We had a similar problem, but using Factory Girl. We solved it like this:

In spec_helper.rb:

 config.include Devise::TestHelpers, :type => :controller 

In the controller specification (wrapper method only):

 def login_user(user) sign_in user end 

Then, in each method you require, you can:

 login_user(Factory(:user)) 

... where you defined the user object in the .rb factories. Not sure if this will work with mocks.

+5
source

The layout will never work. When you pronounce the input, the user is stored in the session (basically, the user class and its identifier). When you access the controller, another user object is retrieved based on the stored data. The best way to solve the problem is to use something that is stored in the object, such as Factory Girl.

+2
source

I got into the same problem. Now I am doing the following:

 before(:each) do # sign_in mock_user request.env['warden'] = mock(Warden, :authenticate => mock_user, :authenticate! => mock_user) end 
+1
source

I created a problem for this here: https://github.com/plataformatec/devise/issues#issue/928 Vote!

0
source

None of them worked for me (MRI 1.9.3-preview1, rails 3.0.1.rc5).

this is the solution i found: http://blog.joshmcarthur.com/post/6407481655/integration-tests-with-devise-and-rspec

0
source

All Articles