Create a gist now

Instantly share code, notes, and snippets.

database cleaner multiple connections single orm outside of rails
RSpec.configure do |config|
config.before(:suite) do
ActiveRecord::Base.establish_connection database['one']
DatabaseCleaner.strategy = :deletion
ActiveRecord::Base.establish_connection config.database['two']
DatabaseCleaner.strategy = :deletion
end
config.before(:each) do
ActiveRecord::Base.establish_connection database['one']
DatabaseCleaner.start
ActiveRecord::Base.establish_connection database['two']
DatabaseCleaner.start
end
config.after(:each) do
ActiveRecord::Base.establish_connection database['one']
DatabaseCleaner.clean
ActiveRecord::Base.establish_connection database['two']
DatabaseCleaner.clean
end
@fguillen
fguillen commented Mar 2, 2012

After two hours of trial and error.. this gist has saved my morning

@mgreenly
Owner
mgreenly commented Mar 2, 2012
@ggalindezb

Thanks you so much! It didn't work out of the box for me, but it did after a bit of tweaking. BTW, this still works in recent (4.2.5.1) versions of Rails/DBCleaner.

# Double db config
other_db = Rails.configuration.database_configuration["other_#{Rails.env}"]
current_db = Rails.configuration.database_configuration[Rails.env]

# Truncate the db, track the transaction for the current test
config.before(:suite) do
  ActiveRecord::Base.establish_connection other_db
  DatabaseCleaner.strategy = :deletion
  ActiveRecord::Base.establish_connection current_db
  DatabaseCleaner.strategy = :deletion
end

config.before(:each) do
  ActiveRecord::Base.establish_connection other_db
  DatabaseCleaner.start
  ActiveRecord::Base.establish_connection current_db
  DatabaseCleaner.start
end

config.after(:each) do
  ActiveRecord::Base.establish_connection other_db
  DatabaseCleaner.clean_with(:deletion)
  ActiveRecord::Base.establish_connection current_db
  DatabaseCleaner.clean_with(:deletion)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment