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

Jos*_*jos 20 testing ruby-on-rails rspec2

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

这是我之前的过滤器:

    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
Run Code Online (Sandbox Code Playgroud)

这是我的测试:

    it "passes the token" do
      get :new, nil,
        :authorization => ActionController::HttpAuthentication::Token.encode_credentials("test_access1")

      assigns(:token).should be "test_access1"
    end
Run Code Online (Sandbox Code Playgroud)

Ser*_*yuk 29

我假设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
Run Code Online (Sandbox Code Playgroud)

您可以稍后将其移动到before :each阻止或支持模块.

更新:

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

get '/path', nil, :authorization => 'string'
Run Code Online (Sandbox Code Playgroud)

应该只在集成测试中工作.对于控制器测试,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
Run Code Online (Sandbox Code Playgroud)

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

# 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)
Run Code Online (Sandbox Code Playgroud)