我花了大约两天没有成功尝试使用Rack :: Test发送自定义标头。我无法将任何标头发送到我的应用中。 我在网上发现了很多类似代码的例子 - 方法(地址,正文,标题),但对我来说,他们根本不工作。
ruby 2.5.1p57(2018-03-29 Revision 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
app中的代码(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"]'
答案 0 :(得分:1)
此代码正常运行:
get '/offers', nil, { 'X-Auth' => 'long key' }
这也是正确的:
header 'X-Auth', 'some key'
get '/offers'
我改变了我在app中查找该标题的方式:
request.get_header('HTTP_X_AUTH') || request.env['X-Auth']
第一个 - get_header是在我用curl调用我的应用程序时触发的,最后一个是request.env - 在测试时。
答案 1 :(得分:0)
您必须使用Rack::Test::Methods#header
(代表Rack::Test::Session#header
):
it 'правильная - get с токеном' do
header 'X-Auth', 'some key'
get '/offers'
$log.debug{ "ENV was: '#{ last_request.env.keys }'" }
end