pstephan1187's avatar

Setting Domain in Route Test with PHPUnit

My app works on multiple domains. Depending on the domain you access the app on, different controllers are called. Here is how the routes file is setup:

Route::group(['domain' => getenv('APP_DOMAIN')], function(){
    //... lots of routes
});

//Catch all
Route::any('{all}', 'SitesPublicController@index')->where('all', '.*');

So if the domain matches the APP_DOMAIN environment variable, then it is handled by controllers set in the Route Group, otherwise it is handled by the SitesPublicController index method.

Everything works just fine in the browser, but when I use PHPUnit, this test fails. It says I am getting a response of 500 instead of 200:

public function testBasicExample()
{
    $response = $this->call('GET', '/');
    $this->assertEquals(200, $response->getStatusCode());
}

I assume it has to do with setting the proper domain? Any ideas?

NOTE: I am using Homestead

0 likes
3 replies
pstephan1187's avatar

@JarekTkaczyk I am using L5 and I have the APP_DOMAIN variable in both the .env file and the phpunit.xml file.

The sixth parameter in the call() method allows you to override the $_SERVER super global. If you follow the code, it eventually leads back to line 325 of Symfony\Component\HttpFoundation\Request:

    public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
    {
        $server = array_replace(array(
            'SERVER_NAME' => 'localhost',
            'SERVER_PORT' => 80,
            'HTTP_HOST' => 'localhost',
            'HTTP_USER_AGENT' => 'Symfony/2.X',
            'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
            'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
            'REMOTE_ADDR' => '127.0.0.1',
            'SCRIPT_NAME' => '',
            'SCRIPT_FILENAME' => '',
            'SERVER_PROTOCOL' => 'HTTP/1.1',
            'REQUEST_TIME' => time(),
        ), $server);

So I tried the following in the test case:

$response = $this->call('GET', '/', [], [], [], ['SERVER_NAME' => 'mydomain.app']);

And it still didn't work.

pstephan1187's avatar
pstephan1187
OP
Best Answer
Level 7

Doing this worked:

$response = $this->call('GET', 'http://mydomain.app/');

Farther down in the Symfony\Component\HttpFoundation\Request class was this code:

 $components = parse_url($uri);
if (isset($components['host'])) {
    $server['SERVER_NAME'] = $components['host'];
    $server['HTTP_HOST'] = $components['host'];
}

Please or to participate in this conversation.