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 28th, 2016 • 12 min read
Maintaining a local server for your projects can become cumbersome and can cause conflicts with your co-workers. Streamlining this with Docker makes sure everyone is in on the same page.
June 3rd, 2014 • 3 min read
Following up on my previous post I got a few questions on how to create modules for your app. Let me show you.
November 7th, 2017 • 3 min read
Boilerplate apps are great. They let you get your next project up and running quickly, and usually provide some form of structure you can follow. But the best boilerplate app is the one you code yourself.