我正在尝试进行以下RSpec测试:
it "should publish the request information" do
post :create, {
:response_code => 200,
:response_base_url => 'http://google.ca',
:response_headers => {:some_site => 'some_site'},
:publish_to_site => {:site_name => 'sample'}
}, {
"Authorization" => "Token token=\"#{YAML.load(File.read('config/application.yml'))['TEST_APP_API_KEY'].to_s}\"",
'Content-Type' => 'application/json'
}
expect(response.status).to eql 200
end
我认为这应该通过,因为API密钥实际存在于系统中,而是回复的响应代码是401
当试图用这种方法发布时它就死了:
def restrict_application_api_access
authenticate_or_request_with_http_token do |token, options|
@api_key = ApplicationApiKey.find_by(api_key: token)
end
end
它去世的具体地点是:
# Right here ...
authenticate_or_request_with_http_token do |token, options|
@api_key = ApplicationApiKey.find_by(api_key: token)
end
它永远不会进入障碍。
所以在此之前我做了一个binding.pry
调查请求信息。有趣的部分是:
"rack.session"=>
{"Authorization"=>"Token token=\"################################\"", "Content-Type"=>"application/json"},
正在传递授权令牌并设置了内容类型,甚至也设置了参数:
"action_dispatch.request.request_parameters"=>
{"response_code"=>"200",
"response_base_url"=>"http://google.ca",
"response_headers"=>{"some_site"=>"some_site"},
"publish_to_site"=>{"site_name"=>"sample"}},
"action_dispatch.request.path_parameters"=>{"controller"=>"api/internal/v1/response_analytics", "action"=>"create"},
"action_dispatch.request.flash_hash"=>#<ActionDispatch::Flash::FlashHash:0x007ff84a08c380 @discard=#<Set: {}>, @flashes={}, @now=nil>,
"PATH_INFO"=>"/internal/v1/response_analytics",
我可以从第三方应用程序发出此请求并从发布信息获得200,当我尝试从应用程序中执行此操作时,它在测试中失败并给我401.我设置标题错误?
答案 0 :(得分:1)
正如您的输出所示,您在会话中而不是标题中设置授权和内容类型。
要在您刚刚执行的规范中设置标题
request.headers["Authorization"] = "..."
request.headers["Content-Type"] = "..."
发送请求之前。