diff --git a/changelog/fix_a_false_positive_for_naming_constant_name.md b/changelog/fix_a_false_positive_for_naming_constant_name.md new file mode 100644 index 00000000000..c3e2034f43a --- /dev/null +++ b/changelog/fix_a_false_positive_for_naming_constant_name.md @@ -0,0 +1 @@ +* [#11865](https://github.com/rubocop/rubocop/pull/11865): Fix an error for `Naming/ConstantName` when assigning a constant from an empty branch of `else`. ([@koic][]) diff --git a/lib/rubocop/cop/naming/constant_name.rb b/lib/rubocop/cop/naming/constant_name.rb index 2c045aaee6d..d8cfe17b221 100644 --- a/lib/rubocop/cop/naming/constant_name.rb +++ b/lib/rubocop/cop/naming/constant_name.rb @@ -76,7 +76,7 @@ def allowed_conditional_expression_on_rhs?(node) end def contains_constant?(node) - node.branches.any?(&:const_type?) + node.branches.compact.any?(&:const_type?) end end end diff --git a/spec/rubocop/cop/naming/constant_name_spec.rb b/spec/rubocop/cop/naming/constant_name_spec.rb index f2229f999f7..b5bd69bbc80 100644 --- a/spec/rubocop/cop/naming/constant_name_spec.rb +++ b/spec/rubocop/cop/naming/constant_name_spec.rb @@ -114,6 +114,15 @@ RUBY end + it 'does not register an offense when assigning a constant from an empty branch of `else`' do + expect_no_offenses(<<~RUBY) + CONST = if condition + foo + else + end + RUBY + end + context 'when a rhs is a conditional expression' do context 'when conditional branches contain only constants' do it 'does not check names' do