DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Custom Headers In Rails Tests

  • submit to reddit
        From time to time you may need to set headers in your functional tests that aren't supported by the @request object.  I had to set up my request with Basic authentication.

Add an extension to the TestRequest class in the test/test_helper.rb file:

class ActionController::TestRequest 
  def set_header(name, value)
    @env[name] = value

Then set values as required in your functional test.

def test_index
  @request.set_header "HTTP_AUTHORIZATION", "Basic " + Base64.encode64('testuser:testpass')
  get :index
  assert_response :success
  assert_template "index"


Snippets Manager replied on Thu, 2007/10/25 - 7:34pm

This is silly, why wouldn't you just use @request.env directly? @request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64.encode64("testuser:testpass") Your snipped add unnecessary work and confusion (you say you're setting a header, but really it's an environment variable)