编写HTTP摘要式身份验证的测试/方法

时间:2012-11-17 00:51:16

标签: ruby-on-rails ruby-on-rails-3 rspec digest-authentication

如何编写一个在rspec测试中使用的方法来访问需要HTTP摘要式身份验证的用户名和密码的页面。例如,这个测试...

it "edit" do
  http_login
  post :edit, id: @post
  assigns[:post].should eq(@post)
end

需要http_login方法是这样的......

def http_login

 user = {"username" => 
 Digest::MD5.hexdigest(["username","Application","password"].join(":"))} 

 request.env['HTTP_AUTHORIZATION'] = 
 ActionController::HttpAuthentication::Digest.encode_credentials(?,?,?,?)
end

我的问题是我在编码凭证的四个参数中添加了什么。参数将是http_method, credentials, password, password_is_ha1,但我不确定如何在测试中编写http_methodcredentials

2 个答案:

答案 0 :(得分:2)

此处的解决方案:https://gist.github.com/1282275

在这里重新发现后代

# Adds support for http digest authentication in Rails 3  
# Inspired by: http://lightyearsoftware.com/2009/04/testing-http-digest-authentication-in-rails/
# Place this code in test/test_helper.rb
# In your test, call authenticate_with_http_digest prior to calling get, post, put or delete  
# Tested with Rails 3.0.7

class ActionController::TestCase
  require 'digest/md5'

  def authenticate_with_http_digest(user = API_USERNAME, password = API_PASSWORD, realm = API_REALM)
    ActionController::Base.class_eval { include ActionController::Testing }

    @controller.instance_eval %Q(
      alias real_process_with_new_base_test process_with_new_base_test

      def process_with_new_base_test(request, response)
        credentials = {
      :uri => request.url,
      :realm => "#{realm}",
      :username => "#{user}",
      :nonce => ActionController::HttpAuthentication::Digest.nonce(request.env['action_dispatch.secret_token']),
      :opaque => ActionController::HttpAuthentication::Digest.opaque(request.env['action_dispatch.secret_token'])
        }
        request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Digest.encode_credentials(request.request_method, credentials, "#{password}", false)

        real_process_with_new_base_test(request, response)
      end
    )
  end
end

答案 1 :(得分:1)

这是RSpec 3.1和Rails 4 HTTP摘要验证测试的解决方案:https://gist.github.com/murbanski/6b971a3edc91b562acaf

相关问题