Testing in Containers

Written by Servers for Hackers / Original link on Aug. 9, 2022

Let's see how to run tests in a Laravel project automatically!

This isn't about how to do Continuous Integration with Laravel, but instead it's best for local development.

Our Goals:

Without Docker:

We can use a utility called pywatch to run a command when files are changed. Here's how we create a new Laravel project and run unit tests automatically when they're updated:

cd ~/Sites
composer create project laravel/laravel docker-testing

cd docker-testing

virtualenv .venv
source .venv/bin/activate
pip install pywatch

pywatch ./vendor/bin/phpunit ./tests/*.php

This works pretty great, but what if we want to test a specific version of PHP when we run our unit tests? Docker can help us there.

With Docker

docker pull php:7.0-cli
# See the new docker images we pulled down
docker images

# Run PHP in a container to run our local phpunit
docker run --rm -v ~/Sites/homestead/docker-testing:/opt php:7.0-cli php /opt/vendor/bin/phpunit /opt/tests

That's good, but let's use pywatch in a container to run unit tests automatically. We'll make our own Docker image. Create a new file named Dockerfile.

FROM php:7.0-cli


RUN apt-get update
RUN apt-get install -y python-pip
RUN pip install -U pip
RUN pip install pywatch


ENTRYPOINT ["pywatch"]

Then we can build our Docker image and try it out:

mkdir docker
cd docker

# create Dockerfile here

# Create a new Docker image named "phptest" and tag it as PHP 7.0
docker build . -t phptest:7.0

# Try running the new image
docker run --rm -it -v ~/Sites/homestead/docker-testing:/opt phptest "php ./vendor/bin/phpunit" ./tests/*.php

This uses the pywatch command set as the ENTRYPOINT and appends the other commands we added. The full command run in the container becomes pywatch "php ./vendor/bin/phpunit" ./tests/*.php, which watches the files in the tests directory ending in .php.


« Build WebSocket infrastructure in-house or outsource to the experts? - JSON API Resources in Laravel »