1
0
Fork 0
mirror of https://github.com/thoughtbot/factory_bot.git synced 2022-11-09 11:43:51 -05:00
thoughtbot--factory_bot/spec/support/macros/define_constant.rb

68 lines
1.5 KiB
Ruby
Raw Permalink Normal View History

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))
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)
created_tables << table_name
2011-08-16 23:30:09 -04:00
connection
rescue Exception => e # rubocop:disable Lint/RescueException
2011-08-16 23:30:09 -04:00
connection.execute("DROP TABLE IF EXISTS #{table_name}")
raise e
2011-08-16 23:30:09 -04:00
end
end
def clear_generated_tables
created_tables.each do |table_name|
clear_generated_table(table_name)
2011-08-16 23:30:09 -04:00
end
created_tables.clear
end
def clear_generated_table(table_name)
ActiveRecord::Base
.connection
.execute("DROP TABLE IF EXISTS #{table_name}")
end
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(
adapter: "sqlite3",
database: ":memory:"
2011-08-16 23:30:09 -04:00
)
end
config.after do
clear_generated_tables
end
end