How to run PHPUnit in Docker in the “pre-commit” hook on the host

Vlad Reshetylo
Towards Dev
Published in
2 min readFeb 13, 2023

--

Now Docker is a standard for PHP development. It helps to keep the same dev environment even in the big team.

PHPUnit is a standard too. The same is true for Git.

And it would be really nice if Git could forbid you to commit code that doesn’t pass tests. And actually, it can do that. There is a special “pre-commit” hook for that.

But sometimes there is a following situation — while the whole development (I mean running the code) goes inside the Docker, Git is being used on the host machine. It’s just more convenient and easy, as it works “out of the box” and allows using external tools like Sublime Merge or GitKraken.

In this case, if we want to run tests in the pre-commit hook, unit tests will also be run on the host machine. Obviously, it brings us environment-incompatibility problems. Someone can say that, in this case, tests should be run in CI/CD, but not every project has such resources.

Luckily, there is a solution. You can run your tests in a temporary docker container while using Git on the host machine.

There are three steps to achieve that:

  1. Create a lightweight image containing only PHP and stuff required for running your unit tests. You need to have the image that starts as fast as possible, and you don’t need stuff like Nginx, nodejs, etc., in a container. Let’s call this image “tests-runner:php8.1” for example
  2. Build the image from step 1
  3. Change your pre-commit bash script to run the docker. You will have to use the following keys: rm (removes container after work), v (mounts directory to the container), t (allocates a pseudo-tty to have colored output).

You must mount your current folder to the container, run PHPUnit, and receive the results.

That's how it can look:

pre-commit.sh example. https://gist.github.com/VladReshet/7df7220fa35da2eca08fd4f58927679a

That’s all! A lightweight container starts in ~1 second, so there is no such big difference with on-host running.

Please let me know if you have other solutions for this issue.

--

--