Created
November 29, 2021 11:32
-
-
Save eugeneius/59b80149a1c293ecf623f2c1cd1e49a1 to your computer and use it in GitHub Desktop.
Intercom's database_cleaner setup (supports initial clean, secondary connections, non-transactional tests, and eliminates an unnecessary query)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "database_cleaner" | |
require "database_cleaner/active_record/deletion" | |
module DatabaseCleaner | |
module ActiveRecord | |
module SelectiveTruncation | |
def information_schema_exists?(_connection) | |
true | |
end | |
end | |
end | |
# These classes have their own database connections which need to be cleaned. | |
# Referencing them here also causes their connection pools to be established, | |
# which needs to happen so that a transaction is wrapped around each test. | |
SECONDARY_CONNECTIONS = [ | |
AbstractClownsDatabase, | |
AbstractDogsDatabase, | |
AbstractWafflesDatabase, | |
].freeze | |
def self.strategy_for_example_group(example_group) | |
if example_group.use_transactional_tests | |
DatabaseCleaner::NullStrategy | |
else | |
:deletion | |
end | |
end | |
def self.set_active_record_cleaner_strategy(strategy) | |
DatabaseCleaner[:active_record].strategy = strategy | |
SECONDARY_CONNECTIONS.each do |connection| | |
DatabaseCleaner[:active_record, { connection: connection }].strategy = strategy | |
end | |
end | |
end | |
RSpec.configure do |config| | |
config.use_transactional_fixtures = true | |
config.before(:suite) do | |
unless ENV["DATABASE_CLEANER_SKIP_INITIAL_CLEAN"] | |
DatabaseCleaner[:active_record].clean_with(:deletion) | |
end | |
end | |
config.before(:each) do |example| | |
strategy = DatabaseCleaner.strategy_for_example_group(example.example_group_instance) | |
DatabaseCleaner.set_active_record_cleaner_strategy(strategy) | |
DatabaseCleaner.start | |
end | |
config.after(:each) do | |
DatabaseCleaner.clean | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment