From 2cff025b91c7bdd15035e364d079e0d2ea01a91e Mon Sep 17 00:00:00 2001 From: Ben Cawkwell Date: Fri, 15 Jan 2021 09:46:20 +0100 Subject: [PATCH] fix: Ensure the DB is still "cleaned" even when transactions are not used In some tests, we might ensure that a transaction has been rolled back (e.g. if an error occurred). Since currently we do not support transactions within other transactions, those tests use the `omit_database_transaction` flag which means the test does not get wrapped in a transaction. The problem is that these tests now leave data lying around after running. Our original plan to solve this was to find a way to still rollback in the app despite already running in a transaction. However Sequel does not support naming a transaction from what I can tell, and anyway there is no way to pass args to the transaction via the `DatabaseCleaner` gem. Going through some issues I found this issue: https://github.com/DatabaseCleaner/database_cleaner/issues/652 Basically this person wants to read data from the DB in another app, but in only some tests. He took the approach of switching "strategy" to accomplish it. I am basically stealing the same idea since it seems to work and was quite trivial. The big downside is that those tests will probably take longer to run, luckily only 5 tests use this flag currently in echo, so this should not be too big of a problem. --- lib/echo_common/rspec/helpers/db_clean_helper.rb | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/echo_common/rspec/helpers/db_clean_helper.rb b/lib/echo_common/rspec/helpers/db_clean_helper.rb index bd8b500..8b6b96d 100644 --- a/lib/echo_common/rspec/helpers/db_clean_helper.rb +++ b/lib/echo_common/rspec/helpers/db_clean_helper.rb @@ -10,12 +10,13 @@ module DbCleanHelper def self.included(base) base.class_eval do around(:each) do |example| - if example.metadata[:omit_database_transaction] + DatabaseCleaner.strategy = if example.metadata[:omit_database_transaction] + :truncation + else + :transaction + end + DatabaseCleaner.cleaning do example.run - else - DatabaseCleaner.cleaning do - example.run - end end end end