集成测试Rails API与基本身份验证

seb*_*iop 3 ruby authentication api ruby-on-rails basic-authentication

我正在尝试使用基本身份验证进行测试签名.我尝试过几种方法.请参阅下面的代码,了解失败尝试和代码的列表.有什么明显的我做错了.谢谢

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
Run Code Online (Sandbox Code Playgroud)

Jes*_*ott 6

看起来你可能正在运行rails3 - Rails3切换到Rack :: test所以语法不同.您传入一个环境哈希来设置您的请求变量,如标头.

尝试类似的东西:

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)
Run Code Online (Sandbox Code Playgroud)

这也可以,但它可能只是一个sinatra:

get '/protected', {}, {'HTTP_AUTHORIZATION' => encode_credentials('go', 'away')}
Run Code Online (Sandbox Code Playgroud)

Sinatra测试信用