繁体   English   中英

使用rspec测试自定义设计和/或监督策略

[英]testing custom devise and/or warden strategy with rspec

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

我该怎么做才能测试这种实现方式。 Rails 3.1.1,设计(最新)等

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

这是通过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 /.../策略目录中。 我还配置了lib,可以通过rails配置自动加载。

从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添加策略时,它应该让我们有一个良好的开端。 我实际上必须实现我认为可以工作的东西然后正确的测试以在事后证明它。 现在我们可以通过相反的方式来做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM