Warning: Creating default object from empty value in /home/brownie/public_html/wp-content/themes/skeptical/functions/admin-hooks.php on line 160

Why pr(), var_dump() and echo are not working in CakePHP 2 test suite?

Many of us use the test environment for development; following the principles of TDD, we write the test case first, and then the code. Working that way, we often need to watch on screen what’s happening with some variables and objects. However, since CakePHP is using PHPUnit, any output coming from a test will not be shown. You can try to call pr(), var_dump(), print() or echo, but none of them will work.

Partial solutions

Looking around, I found this question on Stackoverflow

Some of the proposed solutions where

  • You can run your tests with a --debug parameter, but I prefer to run the tests from the browser and this only works if you run your tests from the console. Thus, I could not find a way to make that configuration available for tests running from the browser.
  • You can call ob_flush() right after the sentence that makes the output. That worked for a while, but after 10 times of write ob_flush() I started to search again for a more permanent solution.

A little better

Then I started to dig into CakePHP core code and, in the file lib/Cake/TestSuite/CakeTestCase.php, you’ll find the method CakeTestCase ::teardown() with this little piece of code:

if (isset($_GET['debug']) && $_GET['debug']) {

That means, you can pass the debug parameter by GET when you run your test and the ob_flush() will be executed. The url should look like this: http://localhost/yourapp/test.php?debug=1

However, I still have to modify the URL by hand, and I’m a fan of automation.

The solution

(Or, at least, a solution I’m happy with)

Just go to /app/webroot/test.php and add this line of code at the top of the file:

$_GET['debug'] = 1;

And that’s it; whenever you run your tests from the browser, you’ll see the output you need.

Potential issues

I asked if it’s possible to make the ob_flush() activated by default when running tests from web. Mark Story replied with a “No”, but I don’t fully understand his answer (sorry, I’m just a basic developer).

You can check it out for yourself here: https://github.com/cakephp/cakephp/commit/b3396538b71340a3ca091af01845a40cc54d148f

Tags: , ,

No comments yet.

Leave a Reply