我看到很多导致了设计和监护人的自定义授权策略,但我之后看到的是使用rspec测试这些解决方案。与此问题类似:Filtering users who are able to sign in with Devise
我可以做些什么来测试这种实现。 Rails 3.1.1,设计(最新)等。
答案 0 :(得分:9)
对于那些将来可能会这样做的人,这是我的解决方案:
这是通过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添加策略时,它应该让我们有一个良好的开端。我实际上必须实现我认为可以工作的东西然后正确的测试以在事后证明它。现在我们可以反过来这样做。