ruby-on-rails - 为 HTTP 摘要认证编写测试/方法

标签 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在测试中实现。

最佳答案

解决方法在这里: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

关于ruby-on-rails - 为 HTTP 摘要认证编写测试/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13426529/

相关文章:

html - 试图将 html 标签拉入我的 Rails 简单形式以拉取 id 标签 css 属性

ruby-on-rails - 语法错误,运行自定义 rake 任务时意外的 tLABEL

ruby-on-rails - Heroku帮助权限被拒绝如何打开文件?

ruby-on-rails - Rails 3 数据类型?

ruby-on-rails - rails : form_for with field for Hash

ruby-on-rails - 我可以使用 RSpec 来测试已部署的站点吗?

ruby-on-rails - 包括 'redirect_to' 方法在内的测试失败,但应用程序运行正常。 Michael Hartl 书第 9.2.2 章 (v 3.2)

ruby-on-rails - Nokogiri XML 和循环不起作用

ruby-on-rails - 如何在 update_attributes 设置为 false 的情况下 stub `current_user`?

ruby-on-rails - 如何模拟 RSpec 期望语法中的类方法?