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

时间:2010-08-12 11:10:46

标签: ruby-on-rails ruby api authentication 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

2 个答案:

答案 0 :(得分: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)

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

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

Sinatra test credit

答案 1 :(得分:4)

这适用于Rails 3

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