[英]Sending custom headers through RSpec
鑒於我的API消費者需要發送客戶HTTP標頭,如下所示:
# curl -H 'X-SomeHeader: 123' http://127.0.0.1:3000/api/api_call.json
然后我可以在before_filter方法中讀取這個標題,如下所示:
# 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測試這個,因為行為有變化:
# 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
將無法找到標頭變量。
使用HTTP_ACCEPT_LANGUAGE標頭嘗試same code
時,它將起作用。 自定義標頭是否在某處過濾?
PS:網絡上的一些示例使用request
而不是@request
。 雖然我不確定當前Rails 3.2 / RSpec 2.14組合中哪一個是正確的 - 兩種方法都不會觸發正確的行為,但兩者都適用於HTTP_ACCEPT_LANGUAGE
。
好吧,對於人們來說可能為時已晚,但只是為了排隊:
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。
您可以直接在get
定義它。
get :api_call, nil, {'HTTP_FOO'=>'BAR'}
我剛剛驗證它在控制台中工作。
RSpec的請求規格在導軌5改變 ,使得自定義headers
和params
現在必須使用鍵-值散列參數來定義。 例如:
之前在Rails 4中 :
it "creates a Widget and redirects to the Widget's page" do
headers = { "CONTENT_TYPE" => "application/json" }
post "/widgets", '{ "widget": { "name":"My Widget" } }', headers
expect(response).to redirect_to(assigns(:widget))
end
現在為Rails 5:
it "creates a Widget and redirects to the Widget's page" do
headers = { "CONTENT_TYPE" => "application/json" }
post "/widgets", :params => '{ "widget": { "name":"My Widget" } }', :headers => headers
expect(response).to redirect_to(assigns(:widget))
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.