/
db_scrub.rb
56 lines (46 loc) · 1.32 KB
/
db_scrub.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
# encoding: utf-8
module Specjour
module DbScrub
begin
require 'rake'
extend Rake::DSL if defined?(Rake::DSL)
if defined?(Rails)
Rake::Task.define_task(:environment) { }
load 'rails/tasks/misc.rake'
load 'active_record/railties/databases.rake'
end
rescue LoadError
Specjour.logger.debug "Failed to load Rails rake tasks"
end
extend self
def drop
Rake::Task['db:drop'].invoke
end
def scrub
connect_to_database
puts "Resetting database #{ENV['TEST_ENV_NUMBER']}"
schema_load_task.invoke
end
protected
def connect_to_database
ActiveRecord::Base.remove_connection
ActiveRecord::Base.configurations = Rails.application.config.database_configuration
ActiveRecord::Base.establish_connection
connection
rescue # assume the database doesn't exist
Rake::Task['db:create'].invoke
end
def connection
ActiveRecord::Base.connection
end
def pending_migrations?
ActiveRecord::Migrator.new(:up, 'db/migrate').pending_migrations.any?
end
def schema_load_task
Rake::Task[{ :sql => "db:test:load_structure", :ruby => "db:test:load" }[ActiveRecord::Base.schema_format]]
end
def tables_to_purge
connection.tables - ['schema_migrations']
end
end
end