Question

How would I write a method to be used in rspec testing to access pages that require a username and password for HTTP Digest Authentication. For example, this test...

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

needs http_login method to be something like this...

def http_login

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

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

My question is what do I put in the four arguments for the encode credentials. The arguments are going to be http_method, credentials, password, password_is_ha1 but I'm unsure how to write http_method and credentials to implement in the tests.

Was it helpful?

Solution

Solution here: https://gist.github.com/1282275

recopied here for posterity

# 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

OTHER TIPS

Here's a solution for RSpec 3.1 and Rails 4 HTTP Digest Auth testing: https://gist.github.com/murbanski/6b971a3edc91b562acaf

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top