Friday, June 17, 2011

Faking authentication in Rails with Devise and RSpec 2

There seems to be alot of different approaches out there on how to fake authentication in your controller specs when using Devise with Rails 3 and RSpec 2. In fact, Devise has even supplied it's own Devise::TestHelpers module for just this scenario. I however was unhappy with that approach and decided to dig a little deeper.

I found that by mocking Warden itself I was able to achieve leaner tests that did not require actually creating an instance of the user i was faking, nor did it require calling several helper methods.

Below is the snippet(gist) we now use in our application to fake authentication in our controller specs. I hope you find it useful.
module AuthenticationHelpers
  # Example usage: login mock_user(Editor)
  def login(user)
    request.env['warden'] = mock(Warden,
                                 :authenticate => user,
                                 :authenticate! => user)
  end
  
  def mock_user(type, stubs={})
    mock_model(type, stubs).as_null_object
  end
end

3 comments:

  1. Thanks. Exactly what I needed to test authentication with Devise.

    ReplyDelete
  2. If you are looking to fake authentication in your features without going to the sign in page, check out the Warden docs: https://github.com/plataformatec/devise/wiki/How-To%3a-Test-with-Capybara

    ReplyDelete
  3. Simply place your chips on the designated positions, spin the wheel, and hope for a winning number. The roulette wheel consists of a stable picket disk slightly convex in bet365 shape. Around its rim are metal partitions known as as|often identified as} separators or frets, and the compartments or pockets between these are called canoes by roulette croupiers. Thirty-six of these compartments, painted alternately pink and black, are numbered nonconsecutively from 1 to 36.

    ReplyDelete