在 Rails 3 中,我们使用了这个不错的小技巧(至少它被包含并且很容易重用)——为 HTTP Digest Authentication 编写测试/方法
但是,这种方法 (process_with_new_base_test) 在 Rails 4 (master) 中完全消失了。有谁知道在 Rails 4 中测试摘要身份验证的正确方法?
在 Rails 3 中,我们使用了这个不错的小技巧(至少它被包含并且很容易重用)——为 HTTP Digest Authentication 编写测试/方法
但是,这种方法 (process_with_new_base_test) 在 Rails 4 (master) 中完全消失了。有谁知道在 Rails 4 中测试摘要身份验证的正确方法?
这里有一个更容易使用的版本:https ://gist.github.com/murbanski/6b971a3edc91b562acaf
我遇到过同样的问题。我通读了 Rails 4 测试用例并构建了以下解决方案。无论如何,它都不是完美的,但它可以在我的测试环境中使用。它是原始authenticate_with_http_digest
辅助方法的嵌入式解决方案。
要点在这里: https ://gist.github.com/illoyd/9429839
对于后代:
# This should go into spec/support/auth_spec_helpers.rb (if you are using RSpec)
module AuthSpecHelpers
##
# Convenience method for setting the Digest Authentication details.
# To use, pass the username and password.
# The method and target are used for the initial request to get the digest auth headers. These will be translated into 'get :index' for example.
# The final 'header' parameter sets the request's authentication headers.
def authenticate_with_http_digest(user, password, method = :get, target = :index, header = 'HTTP_AUTHORIZATION')
@request.env[header] = encode_credentials(username: user, password: password, method: method, target: target)
end
##
# Shamelessly stolen from the Rails 4 test framework.
# See https://github.com/rails/rails/blob/a3b1105ada3da64acfa3843b164b14b734456a50/actionpack/test/controller/http_digest_authentication_test.rb
def encode_credentials(options)
options.reverse_merge!(:nc => "00000001", :cnonce => "0a4f113b", :password_is_ha1 => false)
password = options.delete(:password)
# Perform unauthenticated request to retrieve digest parameters to use on subsequent request
method = options.delete(:method) || 'GET'
target = options.delete(:target) || :index
case method.to_s.upcase
when 'GET'
get target
when 'POST'
post target
end
assert_response :unauthorized
credentials = decode_credentials(@response.headers['WWW-Authenticate'])
credentials.merge!(options)
path_info = @request.env['PATH_INFO'].to_s
uri = options[:uri] || path_info
credentials.merge!(:uri => uri)
@request.env["ORIGINAL_FULLPATH"] = path_info
ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1])
end
##
# Also shamelessly stolen from the Rails 4 test framework.
# See https://github.com/rails/rails/blob/a3b1105ada3da64acfa3843b164b14b734456a50/actionpack/test/controller/http_digest_authentication_test.rb
def decode_credentials(header)
ActionController::HttpAuthentication::Digest.decode_credentials(header)
end
end
# Don't forget to add to rspec's config (spec/spec_helper.rb)
RSpec.configure do |config|
# Include auth digest helper
config.include AuthSpecHelpers, :type => :controller
end
快乐的测试。