Skip to content

Commit ab19423

Browse files
committed
Decouple test models from ActiveRecord
Intention is to allow testing multiple ORMs more easily, with equivalent data.
1 parent 5a78e6e commit ab19423

File tree

4 files changed

+59
-30
lines changed

4 files changed

+59
-30
lines changed

spec/spec_helper.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
NEW_RAILS = Gem.loaded_specs['rails'].version >= Gem::Version.new('6.0')
4545

4646
Dir["#{File.dirname(__FILE__)}/support/*.rb"].each { |file| require file }
47+
Dir["#{File.dirname(__FILE__)}/support/test_models/*.rb"].each { |file| require file }
4748

4849
RSpec.configure do |c|
4950
c.mock_with :rspec
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
module Models
2+
class ModelSpecification
3+
Field = Data.define(:name, :type)
4+
5+
attr_reader :name, :fields, :body
6+
7+
def initialize(klass_name, fields:, &block)
8+
@name = klass_name
9+
@fields = fields.map { |name, type| Field.new(name, type) }
10+
@body = block
11+
end
12+
end
13+
end
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# This file is responsible for one-time set up of ActiveRecord
2+
# 1 - Set ActiveRecord connection & options
3+
# 2 - Delete existing database
4+
# 3 - Expose "TestModels::ActiveRecord.initialize_model" to allow dynamically creating models
5+
require 'active_record'
6+
7+
ActiveRecord::Base.logger = Logger.new($stdout)
8+
ActiveRecord::Base.logger.level = Logger::WARN
9+
ActiveRecord::Base.establish_connection(
10+
'adapter' => defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3',
11+
'database' => 'data.sqlite3',
12+
'pool' => 5,
13+
'timeout' => 5000
14+
)
15+
16+
ActiveRecord::Base.raise_in_transactional_callbacks = true if ActiveRecord::Base.respond_to?(:raise_in_transactional_callbacks)
17+
18+
FileUtils.rm_f('data.sqlite3')
19+
20+
module Models
21+
module ActiveRecord
22+
def self.schema
23+
@schema ||= ::ActiveRecord::Schema.new.tap { |schema| schema.verbose = false }
24+
end
25+
26+
def self.initialize_model(specification)
27+
schema.create_table specification.name.underscore.pluralize do |t|
28+
specification.fields.each do |field|
29+
t.send(field.type, field.name)
30+
end
31+
end
32+
33+
klass = Class.new(::ActiveRecord::Base) do
34+
define_singleton_method(:model_name) do
35+
name = "Models::ActiveRecord::#{specification.name}"
36+
ActiveModel::Name.new(self, nil, name)
37+
end
38+
end
39+
40+
const_set(specification.name, klass)
41+
42+
klass.class_eval(&specification.body)
43+
end
44+
end
45+
end

spec/support/active_record_schema.rb

Lines changed: 0 additions & 30 deletions
This file was deleted.

0 commit comments

Comments
 (0)