12

As part of an API I am building, there is a user authentication method which upon success, returns a payload of useful user information, API token, etc.

In writing functional tests for the controller that handles this, I am running in to an issue testing HTTP Basic auth; I have found numerous blogs that mention the following code should be used to spoof headers for an authentication attempt:

@request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(email, pass)

The issue is that this has no effect; authenticate_with_http_basic does not see the headers and therefore is returning false even in the presence of valid credentials.

Am I missing something?

Note that the app is frozen to Rails 2.2.2 if that is useful in answering.

4

1 回答 1

9

我不确定这是否有帮助,但我只是在自己的应用程序中进行了这些测试之一,除了我使用的是 Rails 2.3.2。

在我的情况下,陷阱是我忘记为用户放入固定装置,所以 crypted_pa​​ssword 不匹配(为什么它有任何价值对我来说仍然是一个谜......我猜 Rails 没有清理运行测试之前的测试数据库?)

class DonglesControllerTest < ActionController::TestCase
  fixtures :users

  test "index api" do
    @request.env['HTTP_AUTHORIZATION'] = encode_credentials('one', 'one')

    get(:index, { :name_contains => 'XXXX0001', :format => 'json' })

    assert_equal 'application/json', @response.content_type
    dongles = ActiveResource::Formats::JsonFormat.decode(@response.body)

    expected_dongles = [
      { 'id' => 1,
        'name' => 'XXXX0001',
        'key_id' => 'usbstor\disk&ven_flash&prod_drive_sm_usb20&rev_1100\0000000000000000&0' }
    ]

    assert_equal expected_dongles, dongles
  end

  private

  # verbatim, from ActiveController's own unit tests
  def encode_credentials(username, password)
    "Basic #{ActiveSupport::Base64.encode64("#{username}:#{password}")}"
  end
end
于 2009-08-11T01:21:52.907 回答