【问题标题】:Rspec Authorization in RailsRails 中的 Rspec 授权
【发布时间】:2013-08-08 15:41:05
【问题描述】:

我正在使用 rails 4 开发一个 rails API,我想对其进行测试。为此,我正在使用 Rspec 框架。

我的 API 有一个如下调用的身份验证方法:

class UsersController < ApplicationController
 # Token authentication
 before_action :set_user, except: [:index, :create]
 before_action :authenticate, except: [:index, :create]
 before_action :authenticate_admin, only: [:index, :create]

 ...
end

然后我有我的 UsersController Rspec:

describe UsersController do
 render_views
 describe "GET /users" do
  it "gets all users" do
   @request.env["AUTHORIZATION"] = "Token token=xxxxxxxxx"
   @request.env["HTTP_ACCEPT"] = "application/json"
   @request.env["CONTENT_TYPE"] = "application/json"
   get  :index
   response.status.should be(200)
  end
 end
end

当我执行测试时,它总是给我同样的结果:

 UsersController GET /users getting all users
 Failure/Error: response.status.should be(200)

   expected #<Fixnum:401> => 200
        got #<Fixnum:803> => 401
 ...

我使用 authenticate_or_request_with_http_token 方法从标头中获取令牌。

如果有人能帮我找到跳过 before_action 方法或正确设置 Authentication 标头的方法,我将不胜感激。

谢谢!

【问题讨论】:

  • 我们将需要查看我假设的身份验证方法来进行您的令牌身份验证。或者也许你正在使用设计或类似的东西?要检查的一件事:你似乎没有在做 :authenticate on index (这是你正在测试的)。
  • 感谢杰西的评论。我复制了代码,但忘记复制索引的身份验证方法,即: before_action :authenticate_admin, only: [:index, :create] 我使用 authenticate_or_request_with_http_token 进行身份验证。谢谢。
  • 我仍然需要查看您的身份验证方法。它将获取令牌,并为您的 current_user 执行查找,对吗?此外,您是否在规范设置期间使用您的令牌创建用户?
  • 我使用基本身份验证。使用用户名和密码,我创建了一个保存在数据库中的 remember_token。然后,在每个请求中,用户必须发送一个标头:“Authorization”,其值:“Token token=”。我尝试做的是使用用户的现有令牌来访问索引方法。
  • 您在规范中的哪个位置创建用户?

标签: ruby-on-rails rspec http-headers


【解决方案1】:

我终于解决了问题。

错误是:

request.env["AUTHORIZATION"] 

必须是

request.env["HTTP_AUTHORIZATION"]. 

除此之外,我从一个不是在我的测试环境中创建的用户那里获得了错误的令牌。

:)

【讨论】:

    猜你喜欢
    • 2017-11-03
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多