/
model_builder.rb
115 lines (96 loc) · 3.03 KB
/
model_builder.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
require_relative 'class_builder'
module UnitTests
module ModelBuilder
def create_table(*args, &block)
ModelBuilder.create_table(*args, &block)
end
def define_model(*args, &block)
ModelBuilder.define_model(*args, &block)
end
def define_model_instance(*args, &block)
define_model(*args, &block).new
end
def define_model_class(*args, &block)
ModelBuilder.define_model_class(*args, &block)
end
def define_active_model_class(*args, &block)
ModelBuilder.define_active_model_class(*args, &block)
end
class << self
def configure_example_group(example_group)
example_group.include(self)
example_group.after do
ModelBuilder.reset
end
end
def reset
clear_column_caches
drop_created_tables
created_tables.clear
defined_models.clear
end
def create_table(table_name, options = {}, &block)
connection =
options.delete(:connection) || DevelopmentRecord.connection
begin
connection.execute("DROP TABLE IF EXISTS #{table_name}")
connection.create_table(table_name, **options, &block)
created_tables << table_name
connection
rescue StandardError => e
connection.execute("DROP TABLE IF EXISTS #{table_name}")
raise e
end
end
def define_model_class(class_name, parent_class: DevelopmentRecord, &block)
ClassBuilder.define_class(class_name, parent_class, &block)
end
def define_active_model_class(class_name, options = {}, &block)
attribute_names = options.delete(:accessors) { [] }
UnitTests::ModelCreationStrategies::ActiveModel.call(
class_name,
attribute_names,
options,
&block
)
end
def define_model(name, columns = {}, options = {}, &block)
model = UnitTests::ModelCreationStrategies::ActiveRecord.call(
name,
columns,
options,
&block
)
model.reset_column_information
defined_models << model
model
end
private
def clear_column_caches
# Rails 4.x
if ::ActiveRecord::Base.connection.respond_to?(:schema_cache)
DevelopmentRecord.connection.schema_cache.clear!
ProductionRecord.connection.schema_cache.clear!
# Rails 3.1 - 4.0
elsif ::ActiveRecord::Base.connection_pool.respond_to?(:clear_cache!)
DevelopmentRecord.connection_pool.clear_cache!
ProductionRecord.connection_pool.clear_cache!
end
end
def drop_created_tables
created_tables.each do |table_name|
DevelopmentRecord.connection.
execute("DROP TABLE IF EXISTS #{table_name}")
ProductionRecord.connection.
execute("DROP TABLE IF EXISTS #{table_name}")
end
end
def created_tables
@_created_tables ||= []
end
def defined_models
@_defined_models ||= []
end
end
end
end