Ruby on rails 如何测试基于令牌的身份验证?

Ruby on rails 如何测试基于令牌的身份验证?,ruby-on-rails,rspec,Ruby On Rails,Rspec,我需要一些测试以下内容的帮助。我正在做关于保护api的RailsCast: 我有一个RequestController和一个before\u filter来检查请求是否有令牌: class RequestsController < ApplicationController include ActionController::MimeResponds include ActionController::HttpAuthentication::Token::ControllerMet

我需要一些测试以下内容的帮助。我正在做关于保护api的RailsCast:

我有一个
RequestController
和一个
before\u filter
来检查请求是否有令牌:

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
结果:
预期成功?要返回true,则返回false


我不明白如何将有效的api_密钥注入到请求中,以便响应计算为true。有什么想法吗?谢谢。

令牌身份验证需要一个
HTTP\u授权
头,格式如下:

Token token="my-api-token"
此外,您还需要在
get:index
行之前设置标题:

request.headers["HTTP_AUTHORIZATION"] = "Token token=\"#{api_key.access_token}\""
get :index
如果您愿意,您可以使用
encode\u凭证
方法:

request.headers["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials(api_key.access_token)

我可以任意命名其他
.headers[]
值吗?例如,我可以执行
request.headers[“username”]=“Joe”
,然后在控制器中使用
request.headers[“username”]
引用它吗?在第二个示例中,您似乎忘记了在访问令牌后添加右括号。
request.headers["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials(api_key.access_token)