Blog / How To Test A Rails Rubygem Against Multiple Databases

How To Test A Rails Rubygem Against Multiple Databases

Chris Oliver

March 30, 2022

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?

The 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

P.S. You might enjoy following me on Twitter.


Comments
Loading...

Want to stay up-to-date with Ruby on Rails?

Join 62,791+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2022 GoRails, LLC. All rights reserved.