2 Ways to Fake $_SERVER Variables in Laravel Feature Tests
Originally published at recca0120.github.io
Scenario
When writing feature tests, you sometimes need to fake $_SERVER variables -- for example, changing REMOTE_ADDR to test IP-related logic.
How To
Laravel's test methods natively support passing server variables.
GET Requests
The second parameter is for server variables:
$this->get('/api/path', [
'REMOTE_ADDR' => '10.1.0.1'
]);
// JSON version
$this->getJson('/api/path', [
'REMOTE_ADDR' => '10.1.0.1'
]);
POST Requests
The third parameter is for server variables (the second is the request body):
$this->post('/api/path', ['foo' => 'bar'], [
'REMOTE_ADDR' => '10.1.0.1'
]);
$this->postJson('/api/path', ['foo' => 'bar'], [
'REMOTE_ADDR' => '10.1.0.1'
]);
Shared Across an Entire Test
If you don't want to pass them on every request, use withServerVariables() to set them once:
$this->withServerVariables(['REMOTE_ADDR' => '10.1.0.1']);
All subsequent requests within the same test method will use these values.
References
- Laravel Docs: HTTP Tests
- Laravel Source: MakesHttpRequests::withServerVariables
- PHP Docs: $_SERVER superglobal
- [Laravel Testing: Assert Final Page Content After a Redirect]({{< ref "/post/laravel-testing-follow-redirects" >}})
- [Laravel Testing: Assert View Data Without Parsing HTML]({{< ref "/post/laravel-testing-view-data" >}})