August 09, 2022

Testing in Containers

See how to run PHP unit tests against different versions of PHP with Docker.

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:

  • Unit test to version of PHP you want
  • Watch for file changes

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

MAINTAINER Chris Fidao

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

WORKDIR /opt

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.

Looking for a deeper dive into Docker?

Sign up here to get a preview of the Shipping Docker course! Learn how to integrate Docker into your applications and develop a workflow to make using Docker a breeze!

All Topics