34

How would you stub Devise in Rails 3 with rSpec. I have a UsersController and a User model. Both of which are associated with Devise at the moment, I'm writing controller specs and I really am having a hard time with my expectations as the Devise sign_in is really jamming up the works.

Any thing will help.

stuartc
  • 2,244
  • 2
  • 24
  • 31
  • 2
    With devise, you can completely stub out the user model: https://github.com/plataformatec/devise/wiki/How-To:-Stub-authentication-in-controller-specs – Flov Sep 02 '12 at 05:49

2 Answers2

74

I found that it is now pretty easy to do this. There was a problem with rspec2 and devise, but is now solved. I guess you would need to update your gems. Then you can write

require 'spec_helper'

describe DoStuffController do
  include Devise::TestHelpers

  before (:each) do
    @user = Factory.create(:user)
    sign_in @user
  end

  describe "GET 'index'" do
    it "should be successful" do
      get 'index'
      response.should be_success
    end
  end
end

[UPDATE] On the devise wiki there is now a detailed (and probably more up-to-date) description.

Alter Lagos
  • 12,090
  • 1
  • 70
  • 92
nathanvda
  • 49,707
  • 13
  • 117
  • 139
  • 7
    Just as a note to others who might come across this. If your using confirmation, make sure your factory defines :confirmed_at or you pass it in. – RyanJM Jul 22 '11 at 17:14
  • 2
    There's a detailed description of this on the devise wiki: https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-(and-rspec) – Kevin Bedell Nov 13 '11 at 14:55
  • @KevinBedell, the URL is almost right - it is missing the last ')'. Thus, the correct URL is [this](https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-%28and-rspec%29) – Zabba May 05 '12 at 20:02
  • I fixed the url in the post as well. – nathanvda May 07 '12 at 07:22
  • 2
    It would be nice not to touch the database on controller tests though... is there any way to mock this behavior instead of actually creating activerecord objects? – Aaron Gibralter Jun 11 '12 at 13:54
9

You can try mocking the underlying warden (https://github.com/wardencommunity/warden/wiki) object which devise relies upon, here is a link to some details on how you can accomplish this with RSpec: http://www.michaelharrison.ws/weblog/?p=349 (entry covers some other topics as well, the solution you want is towards the bottom of the page.)

RamC
  • 1,287
  • 1
  • 11
  • 15