2018-10-07 21:45:51 -04:00
|
|
|
require "active_record"
|
2011-08-16 23:30:09 -04:00
|
|
|
|
|
|
|
module DefineConstantMacros
|
|
|
|
def define_class(path, base = Object, &block)
|
2019-07-12 23:06:02 -04:00
|
|
|
const = stub_const(path, Class.new(base))
|
2021-02-20 16:55:25 -05:00
|
|
|
const.class_eval(&block) if block
|
2019-07-12 23:06:02 -04:00
|
|
|
const
|
2011-08-16 23:30:09 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def define_model(name, columns = {}, &block)
|
|
|
|
model = define_class(name, ActiveRecord::Base, &block)
|
|
|
|
create_table(model.table_name) do |table|
|
2013-01-18 13:27:30 -05:00
|
|
|
columns.each do |column_name, type|
|
|
|
|
table.column column_name, type
|
2011-08-16 23:30:09 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
model
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_table(table_name, &block)
|
|
|
|
connection = ActiveRecord::Base.connection
|
|
|
|
|
|
|
|
begin
|
|
|
|
connection.execute("DROP TABLE IF EXISTS #{table_name}")
|
|
|
|
connection.create_table(table_name, &block)
|
2018-10-05 11:19:48 -04:00
|
|
|
created_tables << table_name
|
2011-08-16 23:30:09 -04:00
|
|
|
connection
|
2019-05-12 22:39:55 -04:00
|
|
|
rescue Exception => e # rubocop:disable Lint/RescueException
|
2011-08-16 23:30:09 -04:00
|
|
|
connection.execute("DROP TABLE IF EXISTS #{table_name}")
|
2019-05-12 22:39:55 -04:00
|
|
|
raise e
|
2011-08-16 23:30:09 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def clear_generated_tables
|
2018-10-05 11:19:48 -04:00
|
|
|
created_tables.each do |table_name|
|
2019-07-12 13:32:50 -04:00
|
|
|
clear_generated_table(table_name)
|
2011-08-16 23:30:09 -04:00
|
|
|
end
|
2018-10-05 11:19:48 -04:00
|
|
|
created_tables.clear
|
|
|
|
end
|
|
|
|
|
2019-07-12 13:32:50 -04:00
|
|
|
def clear_generated_table(table_name)
|
2020-06-05 15:15:18 -04:00
|
|
|
ActiveRecord::Base
|
|
|
|
.connection
|
|
|
|
.execute("DROP TABLE IF EXISTS #{table_name}")
|
2019-07-12 13:32:50 -04:00
|
|
|
end
|
|
|
|
|
2018-10-05 11:19:48 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def created_tables
|
|
|
|
@created_tables ||= []
|
2011-08-16 23:30:09 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
RSpec.configure do |config|
|
|
|
|
config.include DefineConstantMacros
|
|
|
|
|
|
|
|
config.before(:all) do
|
|
|
|
ActiveRecord::Base.establish_connection(
|
2019-05-12 22:39:55 -04:00
|
|
|
adapter: "sqlite3",
|
2020-06-05 15:15:18 -04:00
|
|
|
database: ":memory:"
|
2011-08-16 23:30:09 -04:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
config.after do
|
|
|
|
clear_generated_tables
|
|
|
|
end
|
|
|
|
end
|