Rails API Integration Testing with Basic Authentication

I am trying to get a test signing using basic authentication. I have tried several approaches. See the code below for a list of failed attempts and code. Is there something obvious that 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("someone@somemail.com: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 'someone@somemail.com', '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
+3
source share
2 answers

It looks like you can run rails3 - Rails3 switched to Rack :: test, so the syntax is different. You pass an environment hash to set request variables, such as 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("someone@somemail.com:qwerty123")

get(end_point, params, env)

This can work too, but it can only be a sinatra:

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

Sinatra Verification Certificate

+6

Rails 3

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

Source: https://habr.com/ru/post/1759297/


All Articles