12

作为API我建立的一部分,有一个用户认证方法,其在成功则返回的有用的用户信息,API令牌的有效载荷等测试HTTP基本认证中的Rails 2.2+

在写功能测试处理这个问题的控制器,我正在运行一个测试HTTP基本身份验证的问题;我发现,何况下面的代码应该被用来恶搞头用于认证尝试众多博客:

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

的问题是,这没有任何影响; authenticate_with_http_basic没有看到标题,因此即使在有效凭证的情况下也返回false。

我错过了什么吗?

请注意,如果应用程序有用,应用程序将冻结到Rails 2.2.2。

+2

我只想说明在2011年和Rails 3中。*您所引用的代码完美工作。 – Arsen7 2011-02-09 16:16:02

回答

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