From 83b185f52d575efaf46a58b0ab65702b1b1efa26 Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Wed, 21 Aug 2024 17:36:28 +0200 Subject: [PATCH] Fix an error for `Rails/BulkChangeTable` when the block for `change_table` is empty --- .../fix_error_rails_bulk_change_table.md | 1 + lib/rubocop/cop/rails/bulk_change_table.rb | 4 +-- .../cop/rails/bulk_change_table_spec.rb | 25 +++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 changelog/fix_error_rails_bulk_change_table.md diff --git a/changelog/fix_error_rails_bulk_change_table.md b/changelog/fix_error_rails_bulk_change_table.md new file mode 100644 index 0000000000..3b01fd4dbe --- /dev/null +++ b/changelog/fix_error_rails_bulk_change_table.md @@ -0,0 +1 @@ +* [#1335](https://github.com/rubocop/rubocop-rails/pull/1335): Fix an error for `Rails/BulkChangeTable` when the block for `change_table` is empty. ([@earlopain][]) diff --git a/lib/rubocop/cop/rails/bulk_change_table.rb b/lib/rubocop/cop/rails/bulk_change_table.rb index 09a4b930f2..83ebb9b70e 100644 --- a/lib/rubocop/cop/rails/bulk_change_table.rb +++ b/lib/rubocop/cop/rails/bulk_change_table.rb @@ -140,9 +140,9 @@ def on_send(node) return unless support_bulk_alter? return unless node.command?(:change_table) return if include_bulk_options?(node) - return unless node.block_node + return unless (body = node.block_node&.body) - send_nodes = send_nodes_from_change_table_block(node.block_node.body) + send_nodes = send_nodes_from_change_table_block(body) add_offense_for_change_table(node) if count_transformations(send_nodes) > 1 end diff --git a/spec/rubocop/cop/rails/bulk_change_table_spec.rb b/spec/rubocop/cop/rails/bulk_change_table_spec.rb index 28bd5b6ce6..931afb6b99 100644 --- a/spec/rubocop/cop/rails/bulk_change_table_spec.rb +++ b/spec/rubocop/cop/rails/bulk_change_table_spec.rb @@ -25,6 +25,25 @@ def change end end + shared_examples 'wrong arguments' do + it 'does not register an offense for `change_table` with no block' do + expect_no_offenses(<<~RUBY) + def up + change_table(:users) + end + RUBY + end + + it 'does not register an offense for `change_table` with empty block' do + expect_no_offenses(<<~RUBY) + def up + change_table(:users) do + end + end + RUBY + end + end + shared_examples 'no offense' do it 'does not register an offense when including combinable transformations' do expect_no_offenses(<<~RUBY) @@ -45,6 +64,8 @@ def change end RUBY end + + it_behaves_like 'wrong arguments' end shared_examples 'offense for mysql' do @@ -91,6 +112,8 @@ def change end RUBY end + + it_behaves_like 'wrong arguments' end shared_examples 'offense for postgresql' do @@ -153,6 +176,8 @@ def change end RUBY end + + it_behaves_like 'wrong arguments' end it_behaves_like 'no offense'