[英]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.