Seb*_*oth 20 rspec ruby-on-rails rspec-rails ruby-on-rails-3
鉴于我的API消费者需要发送客户HTTP标头,如下所示:
# curl -H 'X-SomeHeader: 123' http://127.0.0.1:3000/api/api_call.json
Run Code Online (Sandbox Code Playgroud)
然后我可以像这样在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
Run Code Online (Sandbox Code Playgroud)
到目前为止很棒.现在我想使用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
Run Code Online (Sandbox Code Playgroud)
但是,request在ApiController中收到的将无法找到标头变量.
same code使用HTTP_ACCEPT_LANGUAGE标头尝试时,它将起作用.自定义标头是否在某处过滤?
PS:网络上的一些例子使用request而不是@request.虽然我不确定当前Rails 3.2/RSpec 2.14组合中哪一个是正确的 - 但这两种方法都不会触发正确的行为,但两者都可以兼顾HTTP_ACCEPT_LANGUAGE.
ale*_*cat 24
好吧,对于人们来说可能为时已晚,但只是为了排队:
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
Run Code Online (Sandbox Code Playgroud)
只需使用适当的设置调用request.headers.
Bil*_*han 12
您可以get直接定义它.
get :api_call, nil, {'HTTP_FOO'=>'BAR'}
Run Code Online (Sandbox Code Playgroud)
我刚刚验证它在控制台中工作.
RSpec请求规范在Rails 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
Run Code Online (Sandbox Code Playgroud)
现在针对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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14491 次 |
| 最近记录: |