Creating A Test DB in Dockerized Rails
I ran into all sorts of trouble when trying to create a simple test database for a Dockerized Rails app.
Maybe Docker Compose was not passing the environmental variable RAILS_ENV=test
?
$ docker compose exec -e RAILS_ENV=test web bash
root@b1c40fe16325:/rails# echo $RAILS_ENV
test
Maybe Rails wasn’t picking up RAILS_ENV=test
?
Loading test environment (Rails 7.1.5)
[1] pry(main)> Rails.env
=> "test"
After many frustrating, useless iterations with ChatGPT, I took the time to RTFM:
$ docker compose exec -e RAILS_ENV=test web rails -T | grep "db:create"
bin/rails db:create # Create the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the config). Without RAILS_ENV or when RAILS_ENV is development, it defaults to creating the development and test databases, except when DATABASE_URL is present
The key is here:
it defaults to creating the development and test databases, except when DATABASE_URL is present
And what was in docker-compose.yml
? You guessed it:
- DATABASE_URL=postgres://...
Which means:
Rails_ENV=test
should not be necessary for creating a test DB, because it is the default behaviour ofrails db:create
.- If
DATABASE_URL
is set indocker-compose.yml
, Rails will ignoreRAILS_ENV
anyway.
Therefore, to create a test DB, I simply removed the DATABASE_URL
from docker-compose.yml
.
Published on 25 Nov 2024
all tags
100daysofcode activerecord android annoyances api apt arch array artix atom az3w backend bash blog browser bug callback career ci-cd cli cloud code coding config configuration cp crud cryptography css csv database db design devops django docker email erp feelsgood filter fugitive gif gist git gnome gnome pomodoro grep hebrew http ide isbn-fetcher iso javascript job search js kanban kindle koans learning linkedin linux logger manjaro map markdown microservices mobi mtp neovim nodejs nvchad packages panda pastbin patch portfolio post postgres pytest python rails reduce refactoring reflections rest routes rspec ruby salesforce script scripting security sed shell sql string_replacement study tdd terminal testing tmux ttd version_control vim vim sort walkthrough webdev workflow