Tuesday, January 27, 2009

Unit Testing Cookies in Cake PHP


One problem I came across when building unit tests was trying to check to see if my cookies were setup properly. (Yes I still use cookies.) The problem with trying to unit test a cookie in Cake PHP is that you are only allowed a single page load for the test. A cookie doesn't exist until it is sent to the browser and the browser sends the cookie back with a new page load.

My first thought was to place a conditional in the test case. This would basically be something like:

if (!empty($_COOKIE['id'])) {
$this->assertTrue($_COOKIE['id'] == 100);

}


This method would require you to have to reload the page to properly test cookies. The first page load will consist of 0 tests. The next page load will consist of 1 test. But this method didn't seem like the best way to go about it.

Then I discovered the PHP function: headers_list().

Headers List will return all the headers that you are about to send to the browser in an array format. This was the solution!

Now I can test what the function is expected to send to the browser (which is independent of the browser actually accepting the cookie or not). Here's a sample of what I did.

function testStoreCookie() {
$this->Controller->storeCookie(100);
$header_list = headers_list();
$cookie_true = false;
foreach($header_list as $item) {

$cookie_true = is_string(stristr($item, "Set-Cookie: id=100")) || $cookie_true;
}

$this->assertTrue($cookie_true);
}


There you have it! You can now test setting cookies without reloading the page.

No comments: