2012-08-13 34 views
4

應客戶的要求,每當應用程序檢測到來自不同IP地址的同一用戶的兩個活動會話時,我必須實施通知電子郵件。你如何測試這個?如何在Rails中測試多個IP地址的登錄

+1

+1我沒有這方面的實際用途,但我真的很感興趣的答案:) – 2012-08-13 23:36:16

回答

1

創建集成測試的測試/集成/ multiple_ip_test.rb

require 'test_helper' 

@@default_ip = "127.0.0.1" 

class ActionController::Request 
    def remote_ip 
    @@default_ip 
    end 
end 

class MultipleIpTest < ActionDispatch::IntegrationTest 
    fixtures :all 

    test "send email notification if login from different ip address" do 
    post_via_redirect login_path, 
         :user => {:username => "john", :password => "test"} 
    assert_equal "https://stackoverflow.com/users/john", path 

    reset! 
    @@default_ip = "200.1.1.1" 
    post_via_redirect login_path, 
         :user => {:username => "john", :password => "test"} 
    assert_equal "https://stackoverflow.com/users/john", path 
    assert_equal 1, ActionMailer::Base.deliveries.size 
    end 
end 

集成測試看上去很像功能測試,但也有一些差異。您不能使用@request來更改原始IP地址。這就是爲什麼我必須打開ActionController::Request類並重新定義remote_ip方法。

因爲對post_via_redirect的響應始終爲200,而不是使用assert_response :redirect,所以我使用URL來驗證用戶是否已成功登錄。

致電reset!是開始新會話所必需的。

有關集成測試的介紹,請在測試中檢查Rails Guides,但不幸的是,他們沒有提及reset!方法。

+0

我不能得到這個解決方案(或任何我試過的排列)工作。我沒有得到任何錯誤,但是當我運行測試時,它不顯示正確的IP。 (我試圖編寫一個測試來驗證Devise爲其「可跟蹤」功能記錄正確的遠程IP)。 – 2015-03-17 15:45:54

+0

也許Devise正在從不同的地方獲取IP地址? ActionDispatch實現'request.remote_ip'和'request.ip'。這[SO問題](http://stackoverflow.com/questions/10997005/whats-the-difference-between-request-remote-ip-and-request-ip-in-rails)解釋了這種差異。我會檢查Devise的源代碼,他們甚至可能會繞過這兩種方法。 – 2015-04-11 19:15:46

0

假設你使用的是一些框架,在這樣的記錄作爲色器件,以下命令將獲得一臺機器的IP遠程訪問你的應用程序:

request.remote_ip 

您需要將自己使用過的IP地址存儲在模型那麼你應該很容易知道他們是否使用不同的IP訪問。

邁克爾G.