RoR:测试使用http令牌身份validation的操作

我正在尝试测试在前置filter中使用http令牌身份validation的控制器。 我的问题是,它使用curl传递令牌是可行的,但在我的测试中它总是失败(我使用的是rspec btw)。 尝试了一个简单的测试,看看是否正在传递令牌,但似乎它没有这样做。 我错过了什么来让测试实际将令牌传递给控制器​​?

这是我之前的filter:

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的东西。 除非你在其他地方有它,否则尝试在这些行中添加一些东西:

 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块或支持模块。

更新:

看到你的评论后,我不得不深入了解。 这是另一个猜测。 这种forms的get

 get '/path', nil, :authorization => 'string' 

应该只在集成测试中工作。 对于控制器测试,auth准备应该如下所示:

 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 

这背后的原因来自各个测试模块的方法签名:

 # 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)