2013-04-19 129 views
2

在Rails 3中,我們使用這樣的小劈(至少它載且容易地再利用) - Writing a Test/Method for HTTP Digest Authentication測試HTTP摘要認證中的Rails 4

但是,這種方法(process_with_new_base_test)在導軌4完全消失(主)。有誰知道在Rails 4中測試摘要認證的正確方法嗎?

Rails 4.0.b1 ActionController::Testing

Rails 3.2.x ActionController::Testing

+0

內特嗨,你最終找到了這個問題的任何有用的文檔或引用? – dodgerogers747

回答

1

我有同樣的問題。我通讀了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 

快樂測試。