3

I'm trying to get a test signing in using basic authentication. I've tried a few approaches. See code below for a list of failed attempts and code. Is there anything obvious I'm doing wrong. Thanks

class ClientApiTest < ActionController::IntegrationTest
  fixtures :all

  test "adding an entry" do

    # No access to @request
    #@request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("[email protected]:qwerty123")

    # Not sure why this didn't work
    #session["warden.user.user.key"] = [User, 1]

    # This didn't work either
    # url = URI.parse("http://localhost.co.uk/diary/people/1/entries.xml")
    # req = Net::HTTP::Post.new(url.path)
    # req.basic_auth '[email protected]', 'qwerty123'

    post "/diary/people/1/entries.xml", {:diary_entry => {
                                              :drink_product_id => 4,
                                              :drink_amount_id => 1,
                                              :quantity => 3
                                             },
                                        }
    puts response.body
    assert_response 200
  end
end
1
  • Jesse's answer is correct. You should mark is answer as correct. Commented Mar 25, 2011 at 19:57

2 Answers 2

6

It looks like you might be running rails3 -- Rails3 switched over to Rack::test so the syntax is different. You pass in an environment hash to set your request variables like headers.

Try something like:

path = "/diary/people/1/entries.xml"
params = {:diary_entry => {
    :drink_product_id => 4,
    :drink_amount_id => 1,
    :quantity => 3}

env=Hash.new
env["CONTENT_TYPE"] = "application/json"
env["ACCEPT"] = "application/json"
env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("[email protected]:qwerty123")

get(end_point, params, env)

This could work too, but it might be a sinatra only thing:

get '/protected', {}, {'HTTP_AUTHORIZATION' => encode_credentials('go', 'away')}

Sinatra test credit

Sign up to request clarification or add additional context in comments.

1 Comment

How would we do it for a Digest Authentication for Rails3?
4

This works for me in Rails 3

@request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials('username', 'password')
get :index

1 Comment

This doesn't work in integration tests because @request isn't available (mentioned in the original question).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.