Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Always ensure clean db state when mixing feature and other specs (transaction & truncation dbcleaning strategy) running in a random order
# spec/support/database_cleaner.rb
def restore_clean_db_state!
DatabaseCleaner.clean_with :truncation
# load Rails.root.join('db', 'seeds.rb')
RSpec.configuration.db_is_dirty = false
end
def start_transaction!
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.start
end
def rollback_transaction!
DatabaseCleaner.clean
end
RSpec.configure do |config|
config.add_setting :db_is_dirty
config.before :suite do
restore_clean_db_state!
end
config.before :each do |example|
if example.metadata[:type] == :feature
restore_clean_db_state!
else
if RSpec.configuration.db_is_dirty?
restore_clean_db_state!
end
start_transaction!
end
end
config.after :each do |example|
if example.metadata[:type] == :feature
RSpec.configuration.db_is_dirty = true
else
rollback_transaction!
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment