ruby-on-rails - RSpec 请求 - 如何为所有请求设置 http 授权 header

标签 ruby-on-rails rspec request authorization

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

我知道我可以这样做:

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

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

我试过设置request.env在前 block 中,但我得到 no method NilClass error因为请求不存在。

我需要一些方法,也许在 spec-helper , 以全局获取与所有请求一起发送的此 header 。

最佳答案

要将其设置在 before 钩子(Hook)中,您需要像这样访问它

config.before(:each) do
  controller.request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials('mytoken')
end

我也讨厌巨大的哈希,但更喜欢在不同的步骤中明确授权用户。毕竟,这是一个非常关键的部分,并且 .所以我的解决方案是:
#spec/helpers/controller_spec_helpers.rb
module ControllerSpecHelpers
  def authenticate user
    token = Token.where(user_id: user.id).first || Factory.create(:token, user_id: user.id)
    request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials(token.hex)
  end
end

#spec/spec_helper.rb
RSpec.configure do |config|
  ...
  config.include ControllerSpecHelpers, :type => :controller

然后我可以像这样使用它
describe Api::V1::Users, type: :controller do
  it 'retrieves the user' do
    user = create :user, name: "Jane Doe"
    authorize user
    get '/v1/users/janedoe.json'
  end
end

我发现这非常适合测试不同的授权级别。或者,您可以让辅助方法指定授权函数并获得相同的结果,如下所示
#spec/helpers/controller_spec_helpers.rb
module ControllerSpecHelpers
  def authenticate
    controller.stub(:authenticate! => true)
  end
end

但是,为了获得终极速度和控制,您可以将它们结合起来
#spec/helpers/controller_spec_helpers.rb
module ControllerSpecHelpers
  def authenticate user = nil
    if user
      token = Token.where(user_id: user.id).first || Factory.create(:token, user_id: user.id)
      request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials(token.hex)
    else
      controller.stub(:authenticate! => true)
    end
  end
end

然后授权整个 block
#spec/spec_helper.rb
...
RSpec.configure do |config|
  ...
  config.before(:each, auth: :skip) { authenticate }

#**/*_spec.rb
describe Api::V1::Users, type: :controller do
  context 'authorized', auth: :skip do
    ...

关于ruby-on-rails - RSpec 请求 - 如何为所有请求设置 http 授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761544/

相关文章:

ruby-on-rails - Rails 4 Paperclip FactoryGirl 文件上传

ruby-on-rails - 使用 rspec 测试 Draper 增强模型

java - DWR的缺点是什么?

python - 具有多个输入的网络抓取并收集所需的总 margin

javascript - ExpressJS - 删除请求后的res.redirect

ruby-on-rails - 尝试使用 mongoid 作为 orm in rails 连接到 ec2 上的 mongodb 实例

mysql - rails : Can joins be merged when chaining scopes?

ruby-on-rails - 在 rails 3 和 rspec 2 中,如何测试调用 render() 所使用的布局?

ruby-on-rails - Rails 中的一对一或零关联

ruby-on-rails - NoMethodError - 未定义方法 `get' 为 nil :NilClass