RoR:测试使用 http 令牌身份验证的操作 [英] RoR: testing an action that uses http token authentication
问题描述
我正在尝试测试在 before 过滤器中使用 http 令牌身份验证的控制器.我的问题是当我使用 curl 传递令牌时它工作正常,但在我的测试中它总是失败(我使用的是 rspec btw).尝试了一个简单的测试来查看令牌是否被传递,但似乎没有这样做.我是否遗漏了让测试实际将令牌传递给控制器的任何内容?
I'm trying to test a controller that's using an http token authentication in the before filter. My problem is that it works ok wheh I use curl to pass the token, but in my tests it always fails (I'm using rspec btw). Tried a simple test to see if the token was being passed at all, but it seems like it's not doing so. Am I missing anything to get the test to actually pass the token to the controller?
这是我的前置过滤器:
def restrict_access
authenticate_or_request_with_http_token do |token, options|
api_key = ApiKey.find_by_access_token(token)
@user = api_key.user unless api_key.nil?
@token = token #set just for the sake of testing
!api_key.nil?
end
end
这是我的测试:
it "passes the token" do
get :new, nil,
:authorization => ActionController::HttpAuthentication::Token.encode_credentials("test_access1")
assigns(:token).should be "test_access1"
end
推荐答案
我假设 ApiKey 是一个 ActiveRecord 模型,对吗?curl 命令针对开发数据库运行,测试针对测试数据库.我在您的代码段中看不到任何设置 ApiKey 的内容.除非您在其他地方拥有它,否则请尝试按照以下方式添加一些内容:
I'm assuming ApiKey is an ActiveRecord model, correct? curl command runs against development database, and tests go against test db. I can't see anything that sets up ApiKey in your snippets. Unless you have it somewhere else, try adding something along these lines:
it "passes the token" do
# use factory or just create record with AR:
ApiKey.create!(:access_token => 'test_access1', ... rest of required attributes ...)
# this part remains unchanged
get :new, nil,
:authorization => ActionController::HttpAuthentication::Token.encode_credentials("test_access1")
assigns(:token).should be "test_access1"
end
您可以稍后将其移至 before :each
块或支持模块.
You can later move it to before :each
block or support module.
更新:
看到你的评论后,我不得不更深入地研究.这是另一个猜测.这种形式的get
After seeing your comment I had to look deeper. Here's another guess. This form of get
get '/path', nil, :authorization => 'string'
应该只在集成测试中工作.对于控制器测试,身份验证准备应如下所示:
should work only in integration tests. And for controller tests auth preparation should look like this:
it "passes the token" do
request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials("test_access1")
get :new
assigns(:token).should be "test_access1"
end
这背后的原因来自各个测试模块的方法签名:
Reasons behind this come from method signatures for respective test modules:
# for action_controller/test_case.rb
def get(action, parameters = nil, session = nil, flash = nil)
# for action_dispatch/testing/integration.rb
def get(path, parameters = nil, headers = nil)
这篇关于RoR:测试使用 http 令牌身份验证的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!