Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

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!

like image 925
bigmandan Avatar asked Nov 06 '13 18:11

bigmandan


1 Answers

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'));
}
like image 63
bigmandan Avatar answered Nov 14 '22 23:11

bigmandan