作为我正在构建的API的一部分,有一种用户身份验证方法,成功时返回有用的用户信息,API令牌等的有效负载。
在为处理此问题的控制器编写功能测试时,我遇到了测试HTTP Basic auth的问题;我发现很多博客都提到应该使用以下代码来欺骗标头以进行身份验证:
@request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(email, pass)
问题是这没有效果; authenticate_with_http_basic
看不到标题,因此即使存在有效凭据也会返回false。
我错过了什么吗?
请注意,如果在回答时有用,应用程序将被冻结到Rails 2.2.2。
答案 0 :(得分:9)
我不确定这是否有帮助,但我只是在我自己的应用程序中进行了其中一个测试,除了我使用的是Rails 2.3.2。
在我的情况下,陷阱是我忘记为用户输入灯具,所以crypted_password不匹配(为什么它有任何价值对我来说仍然是一个谜......我猜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