Setting HTTP Headers in Symfony Crawler Client


Introduction

I’ve recently created a Symfony application that keeps track of the browser that submitted the form. When developing functional tests for this application, I needed to set the HOST and User-Agent HTTP headers on the client. This article is about how to do that.

Creating the Client

All functional test cases should extend WebTestCase in Symfony as described in the testing documentation. So your class should be written like that and each of your tests should include the word “test” in the function name. So an example might be like so:

<?php
// tests/AppBundle/Functional/DefaultControllerTest.php
namespace tests\AppBundle\Functional;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
   public function testLogin(){
   ...
   }
   ...
}

Where the above file is created in the tests\AppBundle\Functional folder. Then since the class extends WebTestCase, now we can create a client like so:

$client = static::createClient();

This just creates the default client, but doesn’t set any specific headers.

Setting the Headers

You may need various HTTP headers for your application. In my case, I needed Host and User-Agent headers. The parameters of the test client is described in the API documentation, and essentially parameter 2 is an array that is the equivalent of a PHP $_SERVER. So in my case I used code like the following:

$client = static::createClient(array(), array(
        'HTTP_HOST' => 'mySymfonyApp', // Set HOST HTTP Header.
        'HTTP_USER_AGENT' => 'Symfony Browser/1.0', // Set Agent header.
));

Notice in the above code, any header is prefixed with HTTP_, and a dash is replaced with underscore. So then User-Agent becomes: HTTP_USER_AGENT

Now with the above code, it will see the client (User-Agent) as Symfony Browser version 1.0.

Hopefully this helps someone out.

Advertisements

About Alvin Bunk
Hi, I'm a software developer at Taft College.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: