Setting remote IP on Laravel controller tests

Posted: 2022-08-07 12:45:15 by Alasdair Keyes

Direct Link | RSS feed


When building a Laravel website you might want to create allow/block lists based on user's IP or from GeoIp information. This is easy enough using geoip2/geoip2 (https://packagist.org/packages/geoip2/geoip2) but how do you test your code is working correctly with specific IP addresses when writing your functional/integration tests?

At the beginning of a test that requires a custom IP you can add $this->serverVariables = ['REMOTE_ADDR' => '1.2.3.4']; and this will be what your controller sees in the IlluminateHttpRequest object.

public funtion testGeoIpFunctionality(): void
{
    $this->serverVariables = ['REMOTE_ADDR' => '1.2.3.4'];
    $response = $this->get('/website/endpoint');

    $response->assertStatus(200);
    ...
    // other assertions
    ...
}


If you found this useful, please feel free to donate via bitcoin to 1NT2ErDzLDBPB8CDLk6j1qUdT6FmxkMmNz

© Alasdair Keyes

IT Consultancy Services

I'm now available for IT consultancy and software development services - Cloudee LTD.



Happy user of Digital Ocean (Affiliate link)


Version:master-3cbfa44ade


Validate HTML 5