Skip to content

Commit

Permalink
Avoid accidental replacement of main DB model connections
Browse files Browse the repository at this point in the history
  • Loading branch information
kaorukobo committed Feb 20, 2024
1 parent aafa5b2 commit 951eb7e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
7 changes: 5 additions & 2 deletions lib/database_cleaner/active_record/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,11 @@ def lookup_from_connection_pool
end

def establish_connection
::ActiveRecord::Base.establish_connection(connection_hash)
::ActiveRecord::Base
# creates a temporary ActiveRecord class that is unique to connection_hash
ActiveRecord.module_eval("class Temp#{connection_hash.hash.abs} < ::ActiveRecord::Base; self; end")
.tap { |ar_class|
ar_class.establish_connection(connection_hash)
}
end

def database_for(model)
Expand Down
3 changes: 2 additions & 1 deletion spec/database_cleaner/active_record/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,8 @@ module ActiveRecord

it "establishes a connection with it" do
expect(::ActiveRecord::Base).to receive(:establish_connection).with(hash)
expect(strategy.connection_class).to eq ::ActiveRecord::Base
expect(strategy.connection_class).to be < ::ActiveRecord::Base
expect(strategy.connection_class.name).to match /^DatabaseCleaner::ActiveRecord::Temp\d+$/
end
end

Expand Down

0 comments on commit 951eb7e

Please sign in to comment.