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