Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kaorukobo/3175afb6c1d943474f2ab8c795a0e6da to your computer and use it in GitHub Desktop.
Save kaorukobo/3175afb6c1d943474f2ab8c795a0e6da to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
def setcwd_to_tmpdir
require "tmpdir"
tmpdir = Dir.mktmpdir
Dir.chdir(tmpdir)
end
def load_gems
require "bundler/inline"
# TO BE FIXED:
# running with `docker run -v ./work:/work ruby:3.2` cause "timeout is a default gem" error, mentioned at https://github.com/rubygems/rubygems/pull/5529
gemfile(true) do
source 'https://rubygems.org'
gem 'rails', '~> 7.0.0'
gem 'sqlite3'
gem 'pry'
gem 'rspec'
gem 'database_cleaner-active_record', git: "https://github.com/DatabaseCleaner/database_cleaner-active_record.git", ref: "aafa5b2"
end
end
def create_config_database_yml
Dir.mkdir "config"
IO.write("config/database.yml", <<~YAML)
test:
adapter: sqlite3
database: "test.sqlite3"
bar:
adapter: sqlite3
database: "bar.sqlite3"
YAML
end
def setup_activerecord
ActiveRecord::Base.configurations = YAML.load(IO.read("config/database.yml"))
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection :test
eval(<<~RUBY, TOPLEVEL_BINDING)
class ApplicationRecord < ActiveRecord::Base
primary_abstract_class
end
RUBY
end
setcwd_to_tmpdir
load_gems
create_config_database_yml
setup_activerecord
# defines Foo model, which use the connection pool from ApplicationRecord.
def define_foo_model
eval(<<~RUBY, TOPLEVEL_BINDING)
class Foo < ApplicationRecord
connection.exec_query "CREATE TABLE foos (id INTEGER PRIMARY KEY)"
reset_column_information
end
RUBY
end
# defines Bar model, which connects to alternate DB to be cleaned by DatabaseCleaner.
def define_bar_model
eval(<<~RUBY, TOPLEVEL_BINDING)
class Bar < ApplicationRecord
establish_connection :bar
connection.exec_query "CREATE TABLE bars (id INTEGER PRIMARY KEY)"
reset_column_information
end
RUBY
end
RSpec.describe "it" do
it "works" do
define_foo_model
cleaner = DatabaseCleaner::Cleaners.new
cleaner[:active_record, :db => :foo].strategy = :transaction
cleaner[:active_record, :db => :bar].strategy = :transaction
cleaner.start
# define Bar model after `cleaner.clean`
define_bar_model
expect(Foo.connection_pool.connections.size).to eq(1)
expect(Foo.connection_pool.connections[0].transaction_open?).to eq(true)
expect(Bar.connection_pool.connections.size).to eq(1)
# Bar's transaction is not open!
#
# expected: true
# got: false
expect(Bar.connection_pool.connections[0].transaction_open?).to eq(true)
end
end
require "rspec/autorun"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment