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

04.07.2007
| 13266 views |
  • 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
  end
end

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"
end
    

Comments

Snippets Manager replied on Thu, 2007/10/25 - 8: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)