Are you using Supabase, Railway or some other cloud Postgres service for your db and want local tests to be… local? But also not a pain in the butt?
Here’s how I containerized a local Postgres database for running tests from yarn rw test
.
Requirements
You need this installed on your machine:
How to
1. Add docker-compose.yaml
file
Add a docker-compose.yaml
file at the project root with this:
version: '3.7'
services:
postgres:
image: postgres:10.5
restart: always
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
logging:
options:
max-size: 10m
max-file: "3"
ports:
- '5438:5432'
volumes:
- ./api/db/postgres-test-data:/var/lib/postgresql/data
mostly copied from here
You can set the mapped host port (left side of :
) to whatever you like. 5432
is usually taken by some other postgres process so I made it 5438
to avoid collision. You’ll need this port later.
Set up TEST_DATABASE_URL
In .env
and .env.example
, ensure your TEST_DATABASE_URL
is un-commented and points to your dockerized postgres container
TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5438/postgres
Make sure the port matches whatever port you set to the left of the
:
in theport
property indocker-compose.yaml
3. Add a script to start your test db
Add these scripts in package.json
{
"scripts": {
"postgres:up": "docker-compose up -d",
"postgres:down": "docker-compose down"
},
}
4. gitginore your volume
Add the volume dir from docker-compose to your .gitingore
.
.gitignore
api/db/postgres-test-data
Note: This is for extra safety. In reality, this dir should be ignored by default since you won’t have permission to view it when docker adds it, but just in case you run something like sudo chown -R $(whoami):$(whoami) .
in your project, the .gitignore
add makes sure you don’t accidentally push all this junk to GitHub.
5. Start postgres test db before running tests
At the beginning of your dev session, run
yarn postgres:up
This will run a postgres container in the background for your yarn rw test
runs to connect to.
If you need to stop the process, you can run yarn postgres:down
. This might wipe out any data in the db? But it shouldn’t matter since it’s only a container for tests.
Conclusion
I don’t know much about docker but this works so far with no problem for running yarn rw test