If you're building a Rubygem that integrates with Rails and ActiveRecord, you'll probably want to test against multiple databases. This is pretty easy to setup for CI where you can run multiple databases in Docker containers with different steps, but what about local development?
DATABASE_URL is typically used for setting the production database for your Rails app. Hatchbox, Heroku, Render, etc all will set this environment variable for Rails to pick up and use the correct database.
You might not realize that the
DATABASE_URL can also be used for other things like testing!
Instead of running
rails test like normal, you can prepend the
DATABASE_URL env var to change the database.
For example, we can change from the default database to Postgres
DATABASE_URL=postgres://127.0.0.1/test_db rails test
You can even take this a step further and write a script to test each of the databases:
#!/usr/bin/env bash echo "Testing against SQLite3" rails test echo "Testing against PostgreSQL" DATABASE_URL=postgres://127.0.0.1/test_db rails test echo "Testing against MySQL" DATABASE_URL=mysql2://root:@127.0.0.1/test_db rails test