且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Rails 2.2+ 中测试 HTTP 基本身份验证

更新时间:2022-06-25 20:40:08

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

I'm not sure if this helps, but I just made one of these tests in my own application, except I'm using Rails 2.3.2.

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

In my case, the pitfall was that I had forgotten to put in the fixtures for users, so the crypted_password didn't match (why it had any value at all is still a mystery to me... I guess Rails didn't clean the test database before running the test?)

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' => 'usbstordisk&ven_flash&prod_drive_sm_usb20&rev_1100 000000000000000&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