我正在开发一个 rails API,使用 rails 4,我想测试它。为此,我使用了 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 方法从 header 中获取 token 。
如果有人能帮我找到跳过 before_action 方法或正确设置身份验证 header 的方法,我将不胜感激。
谢谢!
最佳答案
我终于解决了这个问题。
错误是:
request.env["AUTHORIZATION"]
必须是
request.env["HTTP_AUTHORIZATION"].
除此之外,我从一个不是在我的测试环境中创建的用户那里得到了错误的 token 。
:)
关于ruby-on-rails - Rails 中的 Rspec 授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18084871/