DEV Community

Recca Tsai
Recca Tsai

Posted on • Originally published at recca0120.github.io

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'
]);
Enter fullscreen mode Exit fullscreen mode

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'
]);
Enter fullscreen mode Exit fullscreen mode

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']);
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)