1# frozen_string_literal: true
2
3require_relative '../../migration_helpers'
4
5module RuboCop
6  module Cop
7    module Migration
8      # Cop that checks if a spec file exists for any migration using
9      # `update_column_in_batches`.
10      class UpdateColumnInBatches < RuboCop::Cop::Cop
11        include MigrationHelpers
12
13        MSG = 'Migration running `update_column_in_batches` must have a spec file at' \
14          ' `%s`.'
15
16        def on_send(node)
17          return unless in_migration?(node)
18          return unless node.children[1] == :update_column_in_batches
19
20          spec_path = spec_filename(node)
21
22          unless File.exist?(File.expand_path(spec_path, rails_root))
23            add_offense(node, location: :expression, message: format(MSG, spec_path))
24          end
25        end
26
27        private
28
29        def spec_filename(node)
30          source_name = node.location.expression.source_buffer.name
31          path = Pathname.new(source_name).relative_path_from(rails_root)
32          dirname = File.dirname(path)
33            .sub(%r{db/(migrate|post_migrate)}, 'spec/migrations')
34          filename = File.basename(source_name, '.rb').sub(/\A\d+_/, '')
35
36          File.join(dirname, "#{filename}_spec.rb")
37        end
38
39        def rails_root
40          Pathname.new(File.expand_path('../../..', __dir__))
41        end
42      end
43    end
44  end
45end
46