When it comes to testing anything that stores IP addresses in Laravel, you may want to mock the return value of request()->ip() to verify that something has been stored correctly, etc.
There are a couple of ways to do this, depending on the kinds of tests you're writing and your preferred style.
I'm using Pest as the testing framework for this article, although the methods covered work with PHPUnit, too.
You can mock any value that Laravel's Request
object returns by adding to the array of data it holds.
Here's how to mock the IP address by overriding the REMOTE_ADDR
value.
it('mocks an IP address via the request', function () {
request()->server->add(['REMOTE_ADDR' => '1.1.1.1']);
expect(request()->ip())->toBe('1.1.1.1');
});
Imagine we have a route that returns the IP address of the user, and we need to test it:
Route::get('/ip', function () {
return response()->json([
'ip' => request()->ip()
]);
});
We can actually set the REMOTE_ADDR
in a slightly different way before we send the request:
it('mocks an IP address with setting server variables', function () {
withServerVariables(['REMOTE_ADDR' => '1.1.1.1']);
get('/ip')
->assertOk()
->assertJsonFragment(['ip' => '1.1.1.1']);
});
Of course, this is interchangeable with the previous method... it just depends on your style.
In the past, I've created my own macro to deal with returning the user's IP address, particularly when I've been working with CDNs like Cloudflare that return the origin IP address under a specific header.
If you're already (or want to) use your own macro method for returning a user's IP address, then you can simply modify this during your test run:
it('mocks an IP address with a macro', function () {
request()->macro('ipAddress', fn () => '1.1.1.1');
expect(request()->ipAddress())->toBe('1.1.1.1');
});
A more niche solution, but useful if you're already doing this.
We've covered several ways to mock the IP address during Laravel tests. They all do the same thing, so pick the one that best fits your style or method of accessing the IP address.