通过 RSpec 发送自定义标头
鉴于我的 API 使用者需要发送这样的客户 HTTP 标头:
Given my API consumers are required to send a customer HTTP header like this:
# curl -H 'X-SomeHeader: 123' http://127.0.0.1:3000/api/api_call.json
然后我可以像这样在 before_filter 方法中读取这个标题:
Then I can read this header in a before_filter method like this:
# app/controllers/api_controller.rb
class ApiController < ApplicationController
before_filter :log_request
private
def log_request
logger.debug "Header: #{request.env['HTTP_X_SOMEHEADER']}"
...
end
end
到目前为止很棒.现在我想使用 RSpec 进行测试,因为行为发生了变化:
So far great. Now I would like to test this using RSpec as there is a change in behavior:
# spec/controllers/api_controller_spec.rb
describe ApiController do
it "should process the header" do
@request.env['HTTP_X_SOMEHEADER'] = '123'
get :api_call
...
end
end
但是,ApiController 中接收到的request
将无法找到头变量.
However, the request
received in ApiController will not be able to find the header variable.
当使用 HTTP_ACCEPT_LANGUAGE 标头尝试 same code
时,它会起作用.是否在某处过滤了自定义标头?
When trying the same code
with the HTTP_ACCEPT_LANGUAGE header, it will work. Are custom headers filtered somewhere?
PS:网络上的一些示例使用 request
而不是 @request
.虽然我不确定在当前的 Rails 3.2/RSpec 2.14 组合中哪一个是正确的 - 这两种方法都不会触发正确的行为,但都可以与 HTTP_ACCEPT_LANGUAGE
一起使用.
PS: Some examples around the web use request
instead of @request
. While I'm not certain which one is correct as of the current Rails 3.2/RSpec 2.14 combination - both methods will not trigger the right behavior, BUT both work with HTTP_ACCEPT_LANGUAGE
as well.
好吧,对于人们来说可能为时已晚,但只是为了排队:
well, maybe too late for people but just to be lined up:
it 'should get profile when authorized' do
user = FactoryGirl.create :user
request.headers[EMAIL_TOKEN] = user.email
request.headers[AUTH_TOKEN] = user.authentication_token
get :profile
response.should be success
end
只需使用适当的设置调用 request.headers.
just call request.headers with appropriate settings.