From 79b08760d66369f43c40c49cc845a68ea9727e6e Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Wed, 5 Jun 2024 23:43:36 +1000 Subject: [PATCH] Address deprecation of `ActiveRecord::Base.connection` in Rails 7.2 (#102) --- lib/database_cleaner/active_record/transaction.rb | 10 ++++++++-- lib/database_cleaner/active_record/truncation.rb | 9 +++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/lib/database_cleaner/active_record/transaction.rb b/lib/database_cleaner/active_record/transaction.rb index b4e71aa8..5e3d7eb2 100644 --- a/lib/database_cleaner/active_record/transaction.rb +++ b/lib/database_cleaner/active_record/transaction.rb @@ -4,10 +4,16 @@ module DatabaseCleaner module ActiveRecord class Transaction < Base def start + connection = if ::ActiveRecord.version >= Gem::Version.new("7.2") + connection_class.lease_connection + else + connection_class.connection + end + # Hack to make sure that the connection is properly set up before cleaning - connection_class.connection.transaction {} + connection.transaction {} - connection_class.connection.begin_transaction joinable: false + connection.begin_transaction joinable: false end diff --git a/lib/database_cleaner/active_record/truncation.rb b/lib/database_cleaner/active_record/truncation.rb index 503e272e..188c93b6 100644 --- a/lib/database_cleaner/active_record/truncation.rb +++ b/lib/database_cleaner/active_record/truncation.rb @@ -30,7 +30,13 @@ def clean private def connection - @connection ||= ConnectionWrapper.new(connection_class.connection) + @connection ||= ConnectionWrapper.new( + if ::ActiveRecord.version >= Gem::Version.new("7.2") + connection_class.lease_connection + else + connection_class.connection + end + ) end def tables_to_truncate(connection) @@ -246,4 +252,3 @@ def tables_with_schema private_constant :ConnectionWrapper end end -