Hello, I'm Alan

Testing Rails within a shipping Docker Container

Thursday, March 12 2015

I really like having solid artefacts that are known good. I’ve seen some people that use different containers for testing than deployment, which to me doesn’t seem like it quite makes sense, and is one more difference between test and deployment.

I do use a few techniques to build my containers quicker, but even if not used my testing technique still works out.

Build script that builds container and runs tests


set -e
set -x

SHA1=`git rev-parse --short HEAD | tr -d "\n"`

trap onexit EXIT

function onexit {
  docker rm -f $DB_CONTAINER  > /dev/null || true

echo "--- Starting database"
docker rm -f $DB_CONTAINER || true #make sure the container doesn't exist to start with
docker run -d -i -t --name $DB_CONTAINER postgres:9.4.0

echo "--- Building container"
docker build -t $DB_CONTAINER:$SHA1 .

echo "--- Running tests"
docker run --rm -i -t --link=$DB_CONTAINER:postgres $CONTAINER_URL:$SHA1 ops/docker_tests

Contents of ops/docker_tests


# This script is ran by build, within a docker container

set -e
set -x

export DATABASE_URL=postgresql://postgres@$POSTGRES_PORT_5432_TCP_ADDR/app_test
bundle exec rake db:setup
bundle exec rake

The only downside is that I need to include the test gems in the project, but for the peace of mind I get, I’m happy to do this.