Running your php/js tests with docker (for GitLab CI and others)
GitLab has a wonderful CI (Continuous Integration) system. Not to use it when pushing your code onto their repos would be a shame ;)
Let me guide you in the marvellous land of automated unit and functional tests.
In this story, we will be using a very common symfony setup:
- Backend: symfony 3.4
- Assets (js and css) are compiled with webpack and webpack encore (see symfony flex)
- phpunit for php tests
Here is what we are going to cover:
- Dockerfile file, used to create your custom docker image where your tests are going to be running
- .gitlab-ci.yml file, used to run your tests on Gitlab
Docker is a program which helps you create sort of virtual machines thanks to a file named Dockerfile.
Isn’t it just great? Thanks to this file and two simple commands, you are going to be able to run your tests effortlessly on any host capable of running a docker instance.
The philosophy here is to take an existing docker image and extend it (or customise it) with our dependencies so that we can run our tests.
Take a look at my Dockerfile (view it on GitHub) and edit it to your needs:
See how we start from a regular php:7.1 image and work our way to a customised one?
Once edited, run the following command to build your image (you might need to create a account on Docker Hub first to get your account name):
docker build -t [YOUR ACCOUNT NAME]/[YOUR IMAGE NAME]:latest .
Once built, push your image to your Docker Hub account with:
docker push [YOUR ACCOUNT NAME]/[YOUR IMAGE NAME]
This will make your custom image available for your tests in GitLab!
Great! Now that we have our custom docker image built and pushed to Docker Hub, let’s take a look at our .gitlab-ci.yml file.
For detailed information on this file, please refer to the official documentation.
Basically when this file is present in your code, GitLab detects it and automatically runs your tests!
Here it what mine looks like (view it on GitHub):
The main things to note here:
- line 1: we use our previously created custom image
- line 32: we tell GitLab to start our phpunit tests
Things can be greatly improved according to me, for example:
- During tests, the `composer install` task takes a long time to execute. Maybe one could find a way to speed this up?
Thanks for reading,
Comments and improvements to my code are more than welcomed!