Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 集成测试Rails API和基本身份验证_Ruby On Rails_Ruby_Api_Authentication_Basic Authentication - Fatal编程技术网

Ruby on rails 集成测试Rails API和基本身份验证

Ruby on rails 集成测试Rails API和基本身份验证,ruby-on-rails,ruby,api,authentication,basic-authentication,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 "

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

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
class ClientApiTest{
:饮料\产品\标识=>4,
:饮料数量id=>1,
:数量=>3
},
}
把反应放在身体上
断言响应200
结束
结束

看起来您可能正在运行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')}

这在Rails 3中对我很有效

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

杰西的回答是正确的。您应该将答案标记为正确。我们如何为Rails3进行摘要身份验证?这在集成测试中不起作用,因为
@request
不可用(在原始问题中提到)。