RoR: testing an action that uses http token authentication

冷暖自知 提交于 2019-12-02 16:46:22

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

You can later move it to before :each block or support module.

UPDATE:

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!