Derokorian
Derokorian

Reputation: 1440

Getting status code response headers for unit tests

I was reading this question and as a result I can successfully test for headers of the form:

header('X-Something: value');
header('Content-Type: text/html');

However, I have code that sets the response code, and I'd like to verify this is working correctly in my units tests too, but they don't come back in the xdebug_get_headers return value. The calls look like:

header('HTTP/1.1 201 Created');
header('HTTP/1.1 422 Unprocessable Entity');

Is there anyway to check for this header as well? Or do I just have to rely on the rest of the return values to prove my controller is working

Upvotes: 2

Views: 963

Answers (2)

l'L'l
l'L'l

Reputation: 47169

You can use the http_response_code() function to return the values you set:

print_r("Response Code: " . http_response_code());

Result:

Response Code: 422

Documentation: http_response_code() - PHP 5.4.0+

Upvotes: 3

Ian Bytchek
Ian Bytchek

Reputation: 9075

If I understand everything correctly, then you are looking for headers_list(), which returns the list of response headers sent (or ready to send), see the docs. Doing the following:

header("X-Sample-Test: foo");
header('Content-type: text/plain');

var_dump(headers_list());

Will output this:

array(3) {
    [0]=>
    string(23) "X-Powered-By: PHP/5.1.3"
    [1]=>
    string(18) "X-Sample-Test: foo"
    [2]=>
    string(24) "Content-type: text/plain"
}

Upvotes: 0

Related Questions