How to test login from multiple IPs in Rails

At the request of the client, I had to send a notification message each time the application detects two active sessions for the same user from different IP addresses. How do you test this?

+4
source share
2 answers

Created integration 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 are very similar to functional tests, but there are some differences. You cannot use @request to change the source IP address. This is why I had to open the ActionController::Request class and override the remote_ip method.

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

Call reset! required to start a new session.

To familiarize yourself with integration tests, check the Rails Guides when testing, unfortunately, they do not mention the reset! method reset! .

+1
source

Assuming you are using some kind of infrastructure to log in, for example devise, the following command will get the IP address of the computer that remotely accesses your application:

 request.remote_ip 

You will need to store the used IP addresses in the model, then you can easily determine if they have access from different IP addresses.

0
source

All Articles