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

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

问题描述

我使用RSpec的要求来测试JSON API,它要求在每个请求的头一个API密钥。

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

我知道我能做到这一点:

I know I can do this:

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

但它是乏味做的每个请求。

But it is tedious to do that for each request.

我试过块之前设置 request.env 中的,但我得到了都没法NilClass误差因为请求不存在。

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

我需要一些方法,也许在规范辅助,在全球范围内得到这头与所有请求发送。

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

推荐答案

我不认为你应该靠头,如果你不测试头本身,你应该存根检查方法是,若HTTP_AUTORIZATION为present并使其除了将测试特定的头规格规格都返回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

类似...
控制器上

something like... on the controller

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天全站免登陆