无法在 rails 集成测试中设置 headers
Unable to set headers in rails integration tests
我有一个集成测试
class UsersTest < ActionDispatch::IntegrationTest
test 'get user' do
get '/users/me', headers: {'Authorization' => 'tokenvalue'}
end
end
然后我有带有方法
的 UsersController
# GET /users/me
def me
puts headers
end
我的输出是
{"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff"}
所以出于某种原因 headers 没有被设置,
我也试过
get '/users/me', nil , headers: {'Authorization' => 'tokenvalue'}
或
get '/users/me', params: {}, headers: { HTTP_AUTHORIZATION: "token" }
但没有任何成功
request.headers['HTTP_AUTHORIZATION'] = "token"
无法在集成测试中访问
你试过了吗?
get '/users/me', nil, {'Authorization' => 'tokenvalue'}
我发现您无法在集成测试中完全访问 request.headers
,但您可以在测试中使用 headers
哈希选项访问它们来验证它们。
我已经解决了这个问题,我有一个方法 index
可以验证 Authorization
header 是在请求时设置的,例如:
def index
if !request.headers['Authorization'].nil?
@boxes = Box.all
else
render json: { error: 'no auth' }, status: :unauthorized
end
end
并且在测试中我正在验证此令牌是否存在,只需访问 headers
并验证 Authorization
header 的值,然后状态,然后是 JSON 响应中给出的错误消息:
test 'should get index if authorization is present' do
get boxes_url, headers: { 'Authorization' => 'hallo' }
assert_response :success
end
test 'should not get index if authorization is not present' do
get boxes_url, headers: { 'Authorization' => nil }
assert_response :unauthorized
body = JSON.parse(response.body)
assert_equal 'no auth', body['error']
end
我有一个集成测试
class UsersTest < ActionDispatch::IntegrationTest
test 'get user' do
get '/users/me', headers: {'Authorization' => 'tokenvalue'}
end
end
然后我有带有方法
的 UsersController # GET /users/me
def me
puts headers
end
我的输出是
{"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff"}
所以出于某种原因 headers 没有被设置, 我也试过
get '/users/me', nil , headers: {'Authorization' => 'tokenvalue'}
或
get '/users/me', params: {}, headers: { HTTP_AUTHORIZATION: "token" }
但没有任何成功
request.headers['HTTP_AUTHORIZATION'] = "token"
无法在集成测试中访问
你试过了吗?
get '/users/me', nil, {'Authorization' => 'tokenvalue'}
我发现您无法在集成测试中完全访问 request.headers
,但您可以在测试中使用 headers
哈希选项访问它们来验证它们。
我已经解决了这个问题,我有一个方法 index
可以验证 Authorization
header 是在请求时设置的,例如:
def index
if !request.headers['Authorization'].nil?
@boxes = Box.all
else
render json: { error: 'no auth' }, status: :unauthorized
end
end
并且在测试中我正在验证此令牌是否存在,只需访问 headers
并验证 Authorization
header 的值,然后状态,然后是 JSON 响应中给出的错误消息:
test 'should get index if authorization is present' do
get boxes_url, headers: { 'Authorization' => 'hallo' }
assert_response :success
end
test 'should not get index if authorization is not present' do
get boxes_url, headers: { 'Authorization' => nil }
assert_response :unauthorized
body = JSON.parse(response.body)
assert_equal 'no auth', body['error']
end