views:

67

answers:

1

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
A: 

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

Jesse Wolgamott