我试图在我的规范中使用ActionDispatch request助手方法设置重要的标题:
RSpec.describe API::V1::FoosController, type: :request do
describe 'GET #index' do
context 'common case' do
request.env.merge!({'HTTP_FOO': 'FOO'})
get api_foos_path, {}, {Accept: Mime::JSON}
end
end
end但是,当涉及到控制器时,这个头(以及通常使用request设置的任何头)消失了:
class API::V1::FoosController < ApplicationController
respond_to :json, :xml
def index
request.env.has_key? 'HTTP_FOO' # false
respond_with serialize_models(Foo.all)
end
# ...
end为什么会发生这种情况,我如何正确地设置它?使用request.header或@request.header设置标头也是如此。
P.S.:我知道我可以将headers设置为Rack::Test::Methods助手的第三个参数,但我不想违反DRY -我只想在那里定义Mime格式。
发布于 2016-02-18 22:02:22
请这样试一试:
request.env['HTTP_FOO_HEADER'] = 'foo header'发布于 2016-02-18 19:41:37
使用controller.request.headers
controller.request.headers['HTTP_FOO'] = 'FOO'我可以验证这种方法在Rails 4.2.5中是否有效,因为这是从实际代码中直接解除的。
我们的测试看起来如下:
describe SomeController, type: :controller do
let(:current_user) { create :user }
before :each do
controller.request.headers['Authorization'] = "APIKey #{current_usser.api_key}"
end
end我们的ApplicationController看起来(或多或少)是这样的:
before_action :authenticate_request
def authenticate_request
key = request.headers['Authorization']
user = User.find_by(api_key: key)
# raise AuthenticationError unless user, etc etc
endhttps://stackoverflow.com/questions/35490874
复制相似问题