Categories
Coding

Running PHPUnit Automatically During Development

Recently I’ve been working on writing unit tests for a new module for the Performance Lab plugin. I realized my workflow was not particularly refined: I kept making a change to the codebase and then switching over to the terminal to re-run PHPUnit by hitting and Enter. I figured this should be done automatically whenever I modify a file.

Turns out it’s easy, thanks to the inotify-tools package. On the Linux environment on my Chromebook I installed it via:

sudo apt-get install inotify-toolsCode language: Bash (bash)

This package includes two commands, inotifywait and inotifywatch. The former is what I need. I just list out the filesystem events I’m interested in, namely modify, create, and delete. Then I supply the directories I’m interested in watching recursively (-r). I put this in a forever while loop, followed by the command to run PHPUnit:

#!/bin/bash
while true; do
	inotifywait -e modify,create,delete -r modules tests
	npm run test-php
doneCode language: Bash (bash)

Now any time I make a change in the modules or tests directories, it will then run the tests and then loop around to wait for another change. To make the loop faster and only execute the tests I care about I add a --group argument to PHPUnit. Now I don’t have to move focus from my editor to the terminal to re-run tests and so my workflow is more efficient.

I realize that PhpStorm also has a File Watcher system, but it seems more tailored to tools like compilers. I also realize that PhpStorm has built-in PHPUnit support and that I should be able to run it via the run/debug configurations, but this wouldn’t be running automatically. In any case, I have yet to figure out how to get that to work with wp-env. (If anyone has figured this out, I’m happy to learn!) Alternatively, instead of using the PHPUnit configuration I could add a shell script integration:

Adding a new Shell Script configuration in PhpStorm to run PHPUnit.

Then I can use a shortcut to run the configuration. But again, this wouldn’t be automatic. I like the simplicity of automatic running from the command line.

Leave a Reply

Your email address will not be published. Required fields are marked *