Skip to content

Instantly share code, notes, and snippets.

@debreczeni
Created November 17, 2014 10:50
Show Gist options
  • Save debreczeni/48898e0958861d43ecbd to your computer and use it in GitHub Desktop.
Save debreczeni/48898e0958861d43ecbd to your computer and use it in GitHub Desktop.
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