ruby-on-rails - 如何测试基于 token 的身份验证?

标签 ruby-on-rails rspec

我需要一些帮助来测试以下内容。我正在做关于保护 api 的 RailsCast:http://railscasts.com/episodes/352-securing-an-api?view=asciicast

我有一个 RequestControllerbefore_filter检查请求是否有 token :

class RequestsController < ApplicationController
  include ActionController::MimeResponds
  include ActionController::HttpAuthentication::Token::ControllerMethods

  before_filter :restrict_access
  respond_to :json

#...

def authenticate
    return restrict_access
  end

  private
  def restrict_access
    authenticate_or_request_with_http_token do |token, options|
      ApiKey.exists?(access_token: token)
    end
  end

end

我失败的 rspec 测试看起来像:
it 'responds successfully to generic request because of key protection' do
    api_key = ApiKey.create
    api_key.save!

    get :index
    request.headers["token"] = api_key.access_token
    expect(response).to be_success # test for the 200 status-code
end

结果:expected success? to return true, got false
我不明白如何将有效的 api_key 注入(inject)请求中,以便响应评估为真。有任何想法吗?谢谢。

最佳答案

token 身份验证需要 HTTP_AUTHORIZATION这种格式的标题:

Token token="my-api-token"

此外,您需要在 get :index 之前设置标题。线:
request.headers["HTTP_AUTHORIZATION"] = "Token token=\"#{api_key.access_token}\""
get :index

您可以使用 encode_credentials如果您愿意,可以使用以下方法:
request.headers["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials(api_key.access_token)

关于ruby-on-rails - 如何测试基于 token 的身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24763505/

相关文章:

ruby-on-rails - 以 rails 形式在循环内嵌套属性的字段

ruby-on-rails - 失败/错误 : require 'rspec/rails' TypeError: wrong argument type Class (expected Module) Rspec V3

ruby-on-rails - Rails/Rspec - 在 Controller 中测试重定向

ruby - 第一次在 ruby​​ 中使用 rspec 进行单元测试

ruby-on-rails - 不小心卸载了rspec

ruby-on-rails - 如何将 psubscribe 与 redis gem 一起使用?

html - 防止用户返回并查看之前提交的表单 Rails

ruby-on-rails - Rspec parallel_test Controller 规范随机失败

ruby-on-rails - Rails 3:缓存到全局变量

ruby - 如何在 rspec 测试中包含 lib 目录