21

我能够使用 Devise 的sign_in方法在我的控制器规格中登录用户。但是现在我要从我的应用程序中删除 Devise,我不太确定如何仅使用 Warden 来获得类似的功能。

我应该如何设置spec/spec_helper.rb和相关spec/support/*.rb文件以使 Warden 在控制器规格内充分运行?

我尝试spec/support/warden.rb使用以下内容设置文件:

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

  config.after do
    Warden.test_reset!
  end
end

然后我有before与此类似的调用来验证user工厂:

before { login_as FactoryGirl.create(:user) }

但这是我一直看到的错误:

NameError:
  undefined method `user' for nil:NilClass

此错误可追溯到我authenticate_user!在控制器中的方法:

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

我将不胜感激任何人都可以提供的任何指导。

4

2 回答 2

31

我不认为这个问题适用于我的情况,但确实适用: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.rbRSpec.configure添加此行以包含新模块:

config.include Warden::Test::ControllerHelpers, type: :controller

第 3 步:要在块中登录用户before,请使用类似于以下的语法:

before { warden.set_user FactoryGirl.create(:user) }

第 4 步:确保request.env['warden']在控制器中引用,而不是env['warden']. 后者不适用于test环境中的控制器规格。

给今井健太郎的帽子小费,我有一天(或在另一种生活中)欠他一杯啤酒!

于 2012-11-16T19:09:50.810 回答
17

您正在尝试做的事情存在一个基本问题。Warden 是一个 Rack 中间件,但 RSpec 控制器规范甚至不包括 Rack,因为这些类型的规范并不意味着运行您的完整应用程序堆栈,而只是您的控制器代码。您可以使用单独的测试来测试您的中间件,但在这种情况下,我认为测试 Warden 本身是否有效是没有意义的。

要测试您是否正确配置了 Warden,您应该使用请求规范或集成规范(黄瓜、水豚或类似的)。

尽管在控制器规范中模拟 Warden 在技术上是可能的,但我认为它并没有给您带来太多好处,同时显着增加了测试代码的复杂性。请记住,Rack 中间件旨在以透明的方式运行,以便您可以轻松地根据需要交换中间件。实际上,您的控制器根本不应该直接依赖于 Warden(也许除了ApplicationController),因此对控制器的 Warden 测试依赖是封装损坏的标志。

我最近遇到了同样的问题,所以我希望这个评论会有用。

于 2013-06-11T18:18:31.703 回答