forked from departurerb/departure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_database.rb
80 lines (67 loc) · 2.21 KB
/
test_database.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
require 'active_record'
require 'active_record/connection_adapters/mysql2_adapter'
# Setups the test database with the schema_migrations table that ActiveRecord
# requires for the migrations, plus a table for the Comment model used throught
# the tests.
#
class TestDatabase
# Constructor
#
# @param config [Hash]
def initialize(config)
@config = config
@database = config['database']
end
# Creates the test database, the schema_migrations and the comments tables.
# It drops any of them if they already exist
def setup
setup_test_database
drop_and_create_schema_migrations_table
end
# Creates the #{@database} database and the comments table in it.
# Before, it drops both if they already exist
def setup_test_database
drop_and_create_test_database
drop_and_create_comments_table
end
# Creates the ActiveRecord's schema_migrations table required for
# migrations to work. Before, it drops the table if it already exists
def drop_and_create_schema_migrations_table
sql = [
"USE #{@database}",
'DROP TABLE IF EXISTS schema_migrations',
'CREATE TABLE schema_migrations ( version varchar(255) COLLATE utf8_unicode_ci NOT NULL, UNIQUE KEY unique_schema_migrations (version)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
]
run_commands(sql)
end
private
attr_reader :config, :database
def drop_and_create_test_database
sql = [
"DROP DATABASE IF EXISTS #{@database}",
"CREATE DATABASE #{@database} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci"
]
run_commands(sql)
end
def drop_and_create_comments_table
sql = [
"USE #{@database}",
'DROP TABLE IF EXISTS comments',
'CREATE TABLE comments ( id bigint(20) NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
]
run_commands(sql)
end
def run_commands(sql)
conn.execute('START TRANSACTION')
sql.each { |str| conn.execute(str) }
conn.execute('COMMIT')
end
def conn
@conn ||= ActiveRecord::Base.mysql2_connection(
host: @config['hostname'],
username: @config['username'],
password: @config['password'],
reconnect: true
)
end
end