Using Sessions in PHPUnit Tests with CakePHP

Posted February 24th, 2012 • 1 min read

I was breaking my head over failing unit tests when trying to test a simple Controller that was saving a new record.

Turned out it was failing only on the command line, while the webversion was passing all the tests.

Luckily, the solution was simple ..

The PHPUnit command line suite apparently outputs contents early, before the session gets initiated.

Solution 1

Add --stderr to the command line:

$ cake testsuite app Controller/YourFancyController --stderr

This will pass the tests again, as it doesn't output contents early to STDOUT. The only "problem" is you won't see the awesome green and red colors in the CLI output anymore.

Solution 2

This is the one I use, as it brings the colors back.

As I'm using my self-contained PHPUnit Install, as found on Github @ PHPUnit-Cake2 I am able to edit the following file: Vendor/PHPUnit/Autoload.php At the very top of this file, initialize the session early:

session_start();

This will pass the tests again, and even better, bring back the colors!

Maybe the session initialization can be done early by putting it in a file by CakePHP itself, but haven't found the right place yet. Any suggestions?

Stay up to date

Want to know when a new post comes out and stay in the loop on tips, tricks and gotchas? Consider signing up for the Mindthecode newsletter.

Comments

Keep reading

November 11th, 2011 • 2 min read
How to install PHPUnit manually for CakePHP 2.0
May 5th, 2014 • 11 min read
Today I want to show a generic workflow and setup I have used a lot lately when working on building apps with Angular. It uses Gulp as a CI system and Browserify to minimize code clutter and maximize awesomeness.
October 8th, 2015 • 2 min read
As I was playing around with the awesome React Native library I encountered a few small hicups getting an app running on an actual device, so here's how I made it work for me.