Module: RSpecPower::DbDumpHelpers

Defined in:
lib/rspec_power/db_dump.rb

Constant Summary collapse

DEFAULT_EXCLUDED_TABLES =
%w[schema_migrations ar_internal_metadata].freeze

Instance Method Summary collapse

Instance Method Details

#dump_database_on_failure(example, options = {}) ⇒ Object



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
# File 'lib/rspec_power/db_dump.rb', line 12

def dump_database_on_failure(example, options = {})
  return unless defined?(::ActiveRecord)

  connection = ::ActiveRecord::Base.connection

  base_dir = resolve_base_dir(options[:dir])
  spec_label = sanitize_label(example.full_description)
  timestamp = Time.now.strftime("%Y%m%d-%H%M%S")

  tables = resolve_tables(connection, options)
  non_empty_tables = tables.select { |t| table_has_rows?(connection, t) }

  return nil if non_empty_tables.empty?

  out_dir = File.join(base_dir, "#{timestamp}_#{spec_label}")
  FileUtils.mkdir_p(out_dir)

  non_empty_tables.each do |table|
    csv_path = File.join(out_dir, "#{table}.csv")
    dump_table_to_csv(connection, table, csv_path)
  end

  (out_dir, example, non_empty_tables)

  puts "[rspec_power] DB dump written to: #{out_dir}"
  puts "[rspec_power] Tables: #{non_empty_tables.join(", ")}" unless non_empty_tables.empty?

  out_dir
rescue => e
  warn "[rspec_power] Failed to dump DB on failure: #{e.class}: #{e.message}"
  nil
end