ActiveRecord without Rails – Connecting and Running Migrations

This is a quick cliff notes of two blog posts I discovered while trying to figure out how to:

  1. Establish a connection to a (SQLite3) database via ActiveRecord outside of a Rails application.
  2. Run migrations to establish a base contents of a test database.

This is useful if you are developing gems that depend on/extend/adapt to ActiveRecord. As an example – there’s this Repository pattern gem I’m working on right now.

I mostly wanted this for tests (RSpec) so I simply added this little snippet to my spec_helper.rb file.

spec_helper.rb

ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'db/test.sqlite3')
ActiveRecord::Migrator.migrate('db/migrate', nil)

The relative paths are based on the gem root (where I’d assume you’re running your specs from anyways). It seems to work as is without doing something similar to the Rails.root dance. So my project looks a bit something like:

  • db
    • migrate
      • 00100_create_users.rb
    • test.sqlite3
  • lib
  • spec

Note the odd “timestamp” on the single migration file. I manually created a sequencing system to mimic the datebased timestamps Rails automatically generates when running the migration generator. I also added the db file (test.sqlite3) to .gitignore for good measure.

If you want to dive deeper into this checkout the blogs I used for inspiration: