Testing in Laravel - running code before testing

Jul 3, 2018 11:07

Running some code before I run a batch of tests was something that I thought was quite common, until I realised I hadn't really done it before. After spending the morning trying to get it working, I have managed to find a solution, which involves some funny qwirks!


If you are here only for the code - its below:


Artisan::command('run-my-tests', function () {

	//-- Check for testing enviroment
	if (\App::environment() !== "testing")
		//-- Fail
		$this->error('Not in testing mode, please use --env=testing');

	//-- This is the area to run your RUN ONCE code before your 
	//-- tests are ran!

	//-- Now - run tests
	$this->info('Start Tests');
	$phpunit = base_path('vendor/bin/phpunit');
	$config = base_path('phpunit.xml');

	$process = new \Symfony\Component\Process\Process($phpunit." --configuration=".$config);
	echo $process->getOutput();

	$this->info('Tests Completed');

Now, to run your tests - run:

> php artisan run-my-tests --env=testing

The How and Why

Why would we want to run code just once before we run a batch of tests yomight ask? I can think of a few reasons:

  • You need to setup an enviroment for testing
  • Seeding a database
  • Resetting something

In my case, I need to reset an external dependancy before testing using it. PHPunit which ships with Laravel handles setup of tests really well when you need to do something before each individual test - but not so good when you need to do something once.

Trying to get something working out the box took me down a rabbit hole of phpunit.xml configutation files, bootstrap files and even writing listeners for the tests - but nothing worked well enough that I would be happy to use.

This brings me to the incredible Symfony component - Process. This component is the muscle behind Artisan on Laravel - so we use it to fire off the phpunit test, and give us the output back into the console so we can view it when running our tests.

We wrap all this in a simple to use Artisan Console command - so now all I need to do is run the one command and my tests run exactly how I need them to!

As usual, if you want to ask me any questions or if you liked this article follow me on Twitter at https://twitter.com/JakeLPrice!