Search code examples
ruby-on-railsruby-on-rails-3rspecwarden

Configuring Warden for use in RSpec controller specs


I was able to use Devise's sign_in method to log in a user in my controller specs. But now that I'm removing Devise from my application, I'm not quite sure how to get similar functionality working with just Warden on its own.

How should I go about setting up spec/spec_helper.rb and related spec/support/*.rb files to get Warden running within controller specs sufficiently?

I've tried setting up a file at spec/support/warden.rb with these contents:

RSpec.configure do |config|
  config.include Warden::Test::Helpers

  config.after do
    Warden.test_reset!
  end
end

Then I have before calls similar to this to authenticate a user factory:

before { login_as FactoryGirl.create(:user) }

But here is the error that I keep seeing:

NameError:
  undefined method `user' for nil:NilClass

This error traces back to my authenticate_user! method in the controller:

def authenticate_user!
  redirect_to login_path, notice: "You need to sign in or sign up before continuing." if env['warden'].user.nil?
end

I'd appreciate any guidance that anyone could provide.


Solution

  • There is a basic problem with what you are trying to do. Warden is a Rack middleware, but RSpec controller specs don't even include Rack, as these types of specs are not meant to run your full application stack, but only your controller code. You can test your middleware with separate tests just for those, but in this case, I don't think it makes sense to test that Warden itself works.

    To test that you have Warden configured correctly, you should use request specs or integration specs (cucumber, capybara or similar).

    Although it is technically possible to mock out Warden in controller specs, I think it is not providing you much benefit while increasing the complexity of your test code significantly. Keep in mind that Rack middleware is meant to operate in a transparent way so that it is easy to swap middleware in and out as you like. Your controller should not be directly dependent on Warden at all (except perhaps for ApplicationController), actually, so having a test dependency on Warden for your controller is a sign of broken encapsulation.

    I ran into this same issue recently so I hope this comment will be useful.