gpt4 book ai didi

ruby - 如何使用 rack::test 发送自定义 header ?

转载 作者:行者123 更新时间:2023-12-03 23:30:00 27 4
gpt4 key购买 nike

我花了大约两天时间尝试使用 Rack::Test 发送自定义 header ,但没有成功。我只是无法将任何 header 发送到我的应用程序中。
我在网上找到了很多类似代码的例子——方法(地址、正文、标题),但对我来说它们根本不起作用。

ruby 2.5.1p57 (2018-03-29 修订版 63029) [x86_64-linux]

# grep rack  Gemfile.lock
rack (2.0.4)
rack-protection (2.0.1)
rack
rack-test (1.0.0)
rack (>= 1.0, < 3)
rack-protection (>= 1.5.0)
rack (~> 2.0)
rack-protection (= 2.0.1)
rack-test

应用程序中的代码(sinatra):
$log = Logger.new STDERR
class MyApi < Sinatra::Application
before do
$log.debug{ "Headers: #{ headers.keys.inspect }" }
end
get '/offers' do
#... some code
end
post '/offers' do
# .. some another code
end
end

规范/api_spec.rb
RSpec.describe MyApi, '/offers' do
include Rack::Test::Methods
def app
MyApi
end

context 'авторизация' do
it 'правильная - get с токеном' do
get '/offers', nil, {
'X-Auth' => 'some key'
}
$log.debug{ "ENV was: '#{ last_request.env.keys }'" }
end
it 'правильная - post с токеном' do
post '/offers', '', {
'Content-Type' => 'application/json; charset: utf-8',
'X-Auth' => 'some long key'
}
end
end
end

输出包含两个测试:
Headers: ["Content-Type"]
...
ENV was: '["rack.version", "rack.input", "rack.errors",
"rack.multithread", "rack.multiprocess", "rack.run_once",
"REQUEST_METHOD", "SERVER_NAME", "SERVER_PORT", "QUERY_STRING",
"PATH_INFO", "rack.url_scheme", "HTTPS", "SCRIPT_NAME", "CONTENT_LENGTH",
"rack.test", "REMOTE_ADDR", "X-Auth", "HTTP_HOST", "HTTP_COOKIE",
"sinatra.commonlogger", "rack.logger", "rack.request.query_string",
"rack.request.query_hash"]'

最佳答案

此代码正在工作:

get '/offers', nil, { 'X-Auth' => 'long key' }

这也是正确的:
header 'X-Auth', 'some key'
get '/offers'

我改变了在应用程序中查找标题的方式:
request.get_header('HTTP_X_AUTH') || request.env['X-Auth']

第一个 - get_header 在我用 curl 调用我的应用程序时触发,最后一个 - request.env - 在测试时触发。

关于ruby - 如何使用 rack::test 发送自定义 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49988893/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com