At the request of a customer, I had to implement sending a notification email every time the application detects two active sessions for the same user from different IP addresses. How do you test this?
-
1+1 I have no practical use for this, but I am genuinely interested in the answer :) – Peter Brown Aug 13 '12 at 23:36
2 Answers
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.
- 421
- 2
- 7
-
I can't get this solution (or any of the permutations that I tried) to work. I don't get any errors, but when I run the test, it doesn't show the right IP. (I am attempting to write a test to verify that Devise records the correct remote IP for its `trackable` functionality.) – Scott Weldon Mar 17 '15 at 15:45
-
Maybe Devise is getting the IP address from a different place?. ActionDispatch implements `request.remote_ip` and `request.ip`. This [SO question](http://stackoverflow.com/questions/10997005/whats-the-difference-between-request-remote-ip-and-request-ip-in-rails) explains the difference. I'd check the source code of Devise, they might even be bypassing these 2 methods. – Braulio Carreno Apr 11 '15 at 19:15
-
Seven years later: for me the request class is actually `ActionDispatch::Request`. If you are having trouble getting this working, try debugging and double-checking the request object type. – Colin Strong Sep 01 '22 at 16:36
Assuming you are using some framework for logging in such as devise, the following command will get the IP of a machine remotely accessing your app:
request.remote_ip
You will need to store their used IPs in the model then you should easily be able to tell if they access with differing IPs.
- 232,980
- 40
- 330
- 338
- 8,597
- 5
- 30
- 51