diff --git a/rubocop/cop/migration/schema_addition_methods_no_post.rb b/rubocop/cop/migration/schema_addition_methods_no_post.rb index 5bb5bb63f0c497d27d1b34a896a32be8eefbf944..c35b82f91573a8861742629c8472dc5889c969eb 100644 --- a/rubocop/cop/migration/schema_addition_methods_no_post.rb +++ b/rubocop/cop/migration/schema_addition_methods_no_post.rb @@ -22,13 +22,25 @@ class SchemaAdditionMethodsNoPost < RuboCop::Cop::Base (send nil? {#{SYMBOLIZED_MATCHER}} ...) PATTERN + def_node_matcher :rolling_back_migration, <<~PATTERN + (def :down ...) + PATTERN + def on_send(node) return unless time_enforced?(node) + return if rolling_back_migration?(node) + on_forbidden_method(node) do add_offense(node, message: MSG) end end + + private + + def rolling_back_migration?(node) + rolling_back_migration(node.parent) + end end end end diff --git a/spec/rubocop/cop/migration/schema_addition_methods_no_post_spec.rb b/spec/rubocop/cop/migration/schema_addition_methods_no_post_spec.rb index fb087269e2dd16e64a7d973d4f5b7ba9675bdb7f..94c0638cf1bd86034f244a302f2d4b02fed735fa 100644 --- a/spec/rubocop/cop/migration/schema_addition_methods_no_post_spec.rb +++ b/spec/rubocop/cop/migration/schema_addition_methods_no_post_spec.rb @@ -3,22 +3,44 @@ require 'rubocop_spec_helper' require_relative '../../../../rubocop/cop/migration/schema_addition_methods_no_post' -RSpec.describe RuboCop::Cop::Migration::SchemaAdditionMethodsNoPost do +RSpec.describe RuboCop::Cop::Migration::SchemaAdditionMethodsNoPost, feature_category: :database do before do allow(cop).to receive(:time_enforced?).and_return true end it "does not allow 'add_column' to be called" do expect_offense(<<~CODE) - add_column - ^^^^^^^^^^ #{described_class::MSG} + def up + add_column(:table, :column, :boolean) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{described_class::MSG} + end CODE end it "does not allow 'create_table' to be called" do expect_offense(<<~CODE) - create_table - ^^^^^^^^^^^^ #{described_class::MSG} + def up + create_table + ^^^^^^^^^^^^ #{described_class::MSG} + end CODE end + + context "when rolling back migration" do + it "allows 'add_column' to be called" do + expect_no_offenses(<<~CODE) + def down + add_column(:table, :column, :boolean) + end + CODE + end + + it "allows 'create_table' to be called" do + expect_no_offenses(<<~CODE) + def down + create_table + end + CODE + end + end end