RSpec 请求 - 如何为所有请求设置 http 授权标头 [英] RSpec Request - How to set http authorization header for all requests

查看:22
本文介绍了RSpec 请求 - 如何为所有请求设置 http 授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 rspec 请求来测试 JSON API,该 API 在每个请求的标头中都需要一个 api-key.

I'm using rspec request to test a JSON API that requires an api-key in the header of each request.

我知道我可以做到:

get "/v1/users/janedoe.json", {}, { 'HTTP_AUTHORIZATION'=>"Token token="mytoken"" }

但是对于每个请求都这样做很乏味.

But it is tedious to do that for each request.

我已经尝试在 before 块中设置 request.env,但是我得到 no method NilClass error 因为请求不存在.

I've tried setting request.env in the before block, but I get the no method NilClass error since request doesn't exist.

我需要一些方法,也许在 spec-helper 中,以全局方式将这个标头与所有请求一起发送.

I need some way, maybe in the spec-helper, to globally get this header sent with all requests.

推荐答案

如果您不测试标头本身,我认为您不应该依赖标头,您应该存根检查 HTTP_AUTORIZATION 是否存在的方法,并且使它对所有规范都返回 true,除了测试特定标题的规范

I don't think you should depend on the header if you are not testing the header itself, you should stub the method that checks if the HTTP_AUTORIZATION is present and make it return true for all specs except the spec that tests that particular header

类似...在控制器上

Controller...
  before_filter :require_http_autorization_token

  methods....

  protected
  def require_http_autorization_token
    something
  end

在规范上

before(:each) do
  controller.stub!(:require_http_autorization_token => true)
end

describe 'GET user' do
  it 'returns something' do
    #call the action without the auth token
  end

  it 'requires an http_autorization_token' do
    controller.unstub(:require_http_autorization_token)
    #test that the actions require that token
  end
end

这样人们就可以忘记令牌并测试您真正想要测试的内容

that way one can forget the token and test what you really want to test

这篇关于RSpec 请求 - 如何为所有请求设置 http 授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆