Skip to content

Instantly share code, notes, and snippets.

@vlado
Last active February 16, 2019 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlado/812948efe4fb0667a964 to your computer and use it in GitHub Desktop.
Save vlado/812948efe4fb0667a964 to your computer and use it in GitHub Desktop.
Stub devise authentication in controller specs with multiple scopes
# Usage:
# fake_sign_in
# fake_sign_in(@user)
# fake_sign_in(@admin)
# fake_sign_in(:admin)
# fake_sign_in(@some_object, :scope => :user)
# fake_sign_out
# fake_sign_out :admin
module ControllerHelpers
def fake_sign_in(resource_or_scope = :user, options = {})
if resource_or_scope.is_a?(Symbol)
scope = resource_or_scope
resource = double(resource_or_scope)
else
resource = resource_or_scope
scope = options[:scope] || resource.class.to_s.underscore
end
# Since we have multiple scopes we need to check if scope option provided to
# authenticate! matches scope that we are logging in
allow(request.env['warden']).to receive(:authenticate!) do |options|
if options[:scope].to_sym == scope.to_sym
resource
else
throw :warden, :scope => scope
end
end
allow(controller).to receive("current_#{scope}").and_return(resource)
end
def fake_sign_out(scope = :user)
allow(request.env['warden']).to receive(:authenticate!).and_throw(:warden, {:scope => scope})
allow(controller).to receive("current_#{scope}").and_return(nil)
end
end
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
config.include ControllerHelpers, :type => :controller
end
@justin808
Copy link

Very nice job! With the other solution posted on the devise wiki, I got this warning:

An expectation of :authenticate! was set on nil. Called from 
/spec/support/controller_macros.rb:25:in `sign_in'. Use allow_message_expectations_on_nil to disable warnings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment