bigmandan
bigmandan

Reputation: 395

How do I inspect response headers in laravel 4 for unit testing?

I have seen many examples on how to set headers on a response but I cannot find a way to inspect the headers of a response.

For example in a test case I have:

public function testGetJson()
{
    $response = $this->action('GET', 'LocationTypeController@index', null, array('Accept' => 'application/json'));
    $this->assertResponseStatus(200);
    //some code here to test that the response content-type is 'application/json'
}

public function testGetXml()
{
    $response = $this->action('GET', 'LocationTypeController@index', null, array('Accept' => 'text/xml'));
    $this->assertResponseStatus(200);
    //some code here to test that the response content-type is 'text/xml'
}

How would I go about testing that the content-type header is 'application/json' or any other content-type? Maybe I'm misunderstanding something?

The controllers I have can do content negation with the Accept header and I want to make sure the content type in the response is correct.

Thanks!

Upvotes: 6

Views: 5243

Answers (4)

joemaller
joemaller

Reputation: 20556

While not specifically about testing, a nice way of getting at Laravel's response object is to register a 'Finish' callback. These are executed just after the response is delivered, right before the app closes. The callback receives the request and the response objects as arguments.

App::finish(function($request, $response) {
    if (Str::contains($response->headers->get('content-type'), 'text/xml') {
        // Response is XML
    }    
}

Upvotes: 3

Piotr Salaciak
Piotr Salaciak

Reputation: 1663

For debugging purposes You could simply use this:

var_dump($response->headers);

Upvotes: 1

bigmandan
bigmandan

Reputation: 395

After some digging around in the Symfony and Laravel docs I was able to figure it out...

public function testGetJson()
{
    // Symfony interally prefixes headers with "HTTP", so 
    // just Accept would not work.  I also had the method signature wrong...
    $response = $this->action('GET', 'LocationTypeController@index',
        array(), array(), array(), array('HTTP_Accept' => 'application/json'));
    $this->assertResponseStatus(200);
    // I just needed to access the public
    // headers var (which is a Symfony ResponseHeaderBag object)
    $this->assertEquals('application/json', 
        $response->headers->get('Content-Type'));
}

Upvotes: 10

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5428

Take a look at the laravel documentation

Request::header('accept');  // or
Response::header('accept');

Retrieving A Request Header

$value = Request::header('Content-Type');

Another way would be to use getallheaders() :

var_dump(getallheaders());

// array(8) {
//   ["Accept"]=>
//   string(63) "text/html[...]"
//   ["Accept-Charset"]=> ...

Upvotes: 1

Related Questions