2

HTTP ダイジェスト認証用のユーザー名とパスワードを必要とするページにアクセスするために rspec テストで使用されるメソッドをどのように記述すればよいでしょうか。例えばこんな試験…

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

私の質問は、エンコード資格情報の 4 つの引数に何を入れるかです。引数は次のようになりますが、テストでの記述方法と実装http_method, credentials, password, password_is_ha1方法がわかりません。http_methodcredentials

4

2 に答える 2

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
于 2012-11-17T04:01:40.647 に答える