I am testing a Laravel 5.1 application which finds the user's location from his / her ip address. The problem is when running tests all the requests seems to come from 127.0.0.1, how can I mock that ip address to test that function ?
If you are the one trying to access the app, you'll always get 127.0.0.1 as the ip address, because you're running on a localhost machine. You'll have to load it into a server to get the different IP's.
//FOR PRODUCTION or SERVER, USE THIS LINE
$ip = $_SERVER['REMOTE_ADDR'];
//FOR LOCALHOST, USE THIS LINE
$ip = 'xxx.xxx.xxx.xxx'; // replace this with your IP address.
class UserIpAddress
{
public function get()
{
return $_SERVER['REMOTE_ADDR'];
}
}
And then while testing swap it using Laravel's service container or maybe using mockery. You can even mock the Laravel's Request class if you are using that.