5

顧客の要求により、アプリケーションが異なる IP アドレスから同じユーザーの 2 つのアクティブなセッションを検出するたびに、通知メールを送信するよう実装する必要がありました。これをどのようにテストしますか?

4

2 に答える 2

1

Created integration test test/integration/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 "/users/john", path

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

Integration tests look a lot like functional tests, but there are some differences. You cannot use @request to change the origin IP address. This is why I had to open the ActionController::Request class and redefine the remote_ip method.

Because the response to post_via_redirect is always 200, instead of using assert_response :redirect I use the URL to verify the user has logged in successfully.

The call to reset! is necessary to start a new session.

For an introduction on integration tests, check the Rails Guides on testing, unfortunately they do not mention the reset! method.

于 2012-08-31T17:41:12.300 に答える
0

devise などのログイン用フレームワークを使用していると仮定すると、次のコマンドはアプリにリモートでアクセスしているマシンの IP を取得します。

request.remote_ip

使用した IP をモデルに保存する必要があります。そうすれば、異なる IP でアクセスするかどうかを簡単に判断できるはずです。

于 2012-08-13T23:37:04.203 に答える