summaryrefslogtreecommitdiff
path: root/spec/support/migrations_helpers/schema_version_finder.rb
blob: b677db7ea26ced8c2164a882d5fd482e08005cd3 (plain)
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
# frozen_string_literal: true

# Sometimes data migration specs require adding invalid test data in order to test
# the migration (e.g. adding a row with null foreign key). Certain db migrations that
# add constraints (e.g. NOT NULL constraint) prevent invalid records from being added
# and data migration from being tested. For this reason, SchemaVersionFinder can be used
# to find and use schema prior to specified one.
#
# @example
#   RSpec.describe CleanupThings, :migration, schema: MigrationHelpers::SchemaVersionFinder.migration_prior(AddNotNullConstraint) do ...
#
# SchemaVersionFinder returns schema version prior to the one specified, which allows to then add
# invalid records to the database, which in return allows to properly test data migration.
module MigrationHelpers
  class SchemaVersionFinder
    def self.migrations_paths
      ActiveRecord::Migrator.migrations_paths
    end

    def self.migration_context
      ActiveRecord::MigrationContext.new(migrations_paths, ActiveRecord::SchemaMigration)
    end

    def self.migrations
      migration_context.migrations
    end

    def self.migration_prior(migration_klass)
      migrations.each_cons(2) do |previous, migration|
        break previous.version if migration.name == migration_klass.name
      end
    end
  end
end