我不认为这个问题适用于我的情况,但确实适用:Stubbing Warden on Controller Tests
事实证明,Warden 没有包含在 RSpec 控制器规范中,所以你需要做一些魔法来解决它。
Kentaro Imai的 Warden博客文章的控制器测试助手特别有用。这是我如何让它为 RSpec 工作的。
第 1 步:创建spec/spec_helper/warden.rb
并粘贴这些内容,这些内容是 Kentaro 从 Devise 派生的:
module Warden
# Warden::Test::ControllerHelpers provides a facility to test controllers in isolation
# Most of the code was extracted from Devise's Devise::TestHelpers.
module Test
module ControllerHelpers
def self.included(base)
base.class_eval do
setup :setup_controller_for_warden, :warden if respond_to?(:setup)
end
end
# Override process to consider warden.
def process(*)
# Make sure we always return @response, a la ActionController::TestCase::Behavior#process, even if warden interrupts
_catch_warden {super} || @response
end
# We need to setup the environment variables and the response in the controller
def setup_controller_for_warden
@request.env['action_controller.instance'] = @controller
end
# Quick access to Warden::Proxy.
def warden
@warden ||= begin
manager = Warden::Manager.new(nil, &Rails.application.config.middleware.detect{|m| m.name == 'Warden::Manager'}.block)
@request.env['warden'] = Warden::Proxy.new(@request.env, manager)
end
end
protected
# Catch warden continuations and handle like the middleware would.
# Returns nil when interrupted, otherwise the normal result of the block.
def _catch_warden(&block)
result = catch(:warden, &block)
if result.is_a?(Hash) && !warden.custom_failure? && !@controller.send(:performed?)
result[:action] ||= :unauthenticated
env = @controller.request.env
env['PATH_INFO'] = "/#{result[:action]}"
env['warden.options'] = result
Warden::Manager._run_callbacks(:before_failure, env, result)
status, headers, body = warden.config[:failure_app].call(env).to_a
@controller.send :render, :status => status, :text => body,
:content_type => headers['Content-Type'], :location => headers['Location']
nil
else
result
end
end
end
end
end
第 2 步:在块中spec/spec_helper.rb
,RSpec.configure
添加此行以包含新模块:
config.include Warden::Test::ControllerHelpers, type: :controller
第 3 步:要在块中登录用户before
,请使用类似于以下的语法:
before { warden.set_user FactoryGirl.create(:user) }
第 4 步:确保request.env['warden']
在控制器中引用,而不是env['warden']
. 后者不适用于test
环境中的控制器规格。
给今井健太郎的帽子小费,我有一天(或在另一种生活中)欠他一杯啤酒!