2

我看到很多导致设计和看守的自定义授权策略,但我特别关注的是使用 rspec 测试这些解决方案。与此问题类似:过滤能够使用 Devise 登录的用户

我能做些什么来测试这种实现。Rails 3.1.1、Devise(最新)等。

4

1 回答 1

12

对于那些将来可能会这样做的人,这是我的解决方案:

这是一个通过 Devise 为身份验证设置新策略的类(它也可以与 Warden 一起使用,只需进行一些小改动)。

require 'devise/strategies/authenticatable'

module Devise
  module Strategies
    class AndroidAuthenticatable < Authenticatable
      def valid? 
        # return true/false
                return valid_params? && valid_headers?
      end 

      def authenticate! 
        failure_message = "Authentication failed for device/user"

        klass = mapping.to # if we're going to come here, we can mock this
        begin
          # code to determine whether or not to authenticate this request
          # if yes, success!(instance of klass)
          # if no, fail!(messsage)
        rescue
          fail!(failure_message) # always fail if not success
        end
      end 

      protected
      def valid_params?
        # params that show whether request should be here
      end

      def valid_headers?
        # headers that determine if request should be here
      end
    end
  end
end

上一课在我的 lib/.../strategies 目录中。我还通过 rails 配置将 lib 配置为自动加载。

从 rspec 方面来看,在我创建了上面的类之后,我写了一些存根/模拟。这是一个基本的 rspec 文件,可帮助您入门。

# I do this in before block or right before test executes
@request = mock(:request)
@strategy = Devise::Strategies::AndroidAuthenticatable.new(nil)
@request.should_receive(:headers).and_return({#hash of the headers you are testing})
@strategy.should_receive(:params).at_least(:once).and_return({#hash of the params})
@strategy.should_receive(:request).and_return(@request)

# Break these up as needed to test failing and successful 
# strategies for your application
lambda {
   @strategy.should be_valid
   @strategy.authenticate!.should eql :success 
}.should_not raise_error

这并不是包罗万象的,但我认为在使用 Warden 或 Devise 添加策略时,它应该让我们有一个良好的开端。实际上,我必须实施我认为可行的方法,然后进行正确的测试以在事后证明它。现在我们也许可以反过来做。

于 2011-11-12T16:11:14.937 回答