Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocks aren't working with RSpec and Devise

I'm working on a Rails 3 web app at the moment with RSpec 2 and we're using Devise for authentication. One (and soon many) of our controllers require the user to be logged in. I know Devise provides the sign_in test helper, but can it be used with an RSpec or Mocha mock object?

I originally tried @user = mock_model(User) where user is the Devise class. This wouldn't work with sign_in :user, @user as get 'index' would redirect to the sign in form.

Does anyone have any experience testing with Devise and can help?

like image 718
Aaron Avatar asked Dec 02 '25 21:12

Aaron


1 Answers

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

In spec_helper.rb:

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

In the controller spec (just a wrapper method):

def login_user(user)
    sign_in user
end

Then in each method you require, you can do:

login_user(Factory(:user))

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

like image 127
Nick Boyce Avatar answered Dec 06 '25 05:12

Nick Boyce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!