Featured image of post 2 Ways to Fake $_SERVER Variables in Laravel Feature Tests

2 Ways to Fake $_SERVER Variables in Laravel Feature Tests

Fake $_SERVER in Laravel feature tests by passing server vars per-request, or use withServerVariables() to apply them globally for the entire test method.

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:

1
2
3
4
5
6
7
8
$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):

1
2
3
4
5
6
7
$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:

1
$this->withServerVariables(['REMOTE_ADDR' => '10.1.0.1']);

All subsequent requests within the same test method will use these values.