5

应客户的要求,每次应用程序检测到来自不同 IP 地址的同一用户的两个活动会话时,我都必须执行发送通知电子邮件。你如何测试这个?

4

2 回答 2

1

创建集成测试 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

集成测试看起来很像功能测试,但也有一些区别。您不能使用@request更改源 IP 地址。这就是为什么我不得不打开ActionController::Request类并重新定义remote_ip方法的原因。

因为响应post_via_redirect始终是 200,assert_response :redirect所以我没有使用 URL 来验证用户是否已成功登录。

调用 toreset!是启动新会话所必需的。

有关集成测试的介绍,请查看Rails Guides on testing,不幸的是他们没有提到该reset!方法。

于 2012-08-31T17:41:12.300 回答
0

假设您正在使用一些框架进行登录,例如设计,以下命令将获取远程访问您的应用程序的机器的 IP:

request.remote_ip

您需要将他们使用的 IP 存储在模型中,然后您应该能够轻松判断他们是否使用不同的 IP 访问。

于 2012-08-13T23:37:04.203 回答