August 29, 2014

cleaning multiple databases with DatabaseCleaner

TL;DR; the database cleaner gem can easily be used to clean multiple databases at once.

I work and maintain some rails projects which connect to multiple databases, some legacy (read: not managed by ActiveRecord), some not.

In order to write proper integration tests you might need to load test data into multiple databases, which in turn leads to the need to have clean databases available for all your test runs.

The following DatabaseCleaner snippet (taken from a project which uses RSpec) sets up cleaning runs for multiple databases:

# spec/support/database_cleaner.rb
database_cleaners = []

RSpec.configure do |config|
  config.before(:suite) do
    database_cleaners << DatabaseCleaner::Base.new(:active_record, { :connection => :db1 })
    database_cleaners << DatabaseCleaner::Base.new(:active_record, { :connection => :db2 })
    database_cleaners.each { |cleaner| cleaner.strategy = :truncation }
  end

  config.before(:each, :js => true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    database_cleaners.each(&:start)
  end

  config.after(:each) do
    database_cleaners.each(&:clean)
  end
end

# spec_helper.rb:
Dir[Rails.root.join("spec", "support", "**", "*.rb")].each { |f| require f }

A similar setup can be used with Minitest as well.

© Raphael Randschau 2010 - 2022 | Impressum