diff --git a/changelog/fix_false_positive_for_style_redundant_self_assignment_branch.md b/changelog/fix_false_positive_for_style_redundant_self_assignment_branch.md new file mode 100644 index 000000000000..a3c599b1f044 --- /dev/null +++ b/changelog/fix_false_positive_for_style_redundant_self_assignment_branch.md @@ -0,0 +1 @@ +* [#10011](https://github.com/rubocop/rubocop/issues/10011): Fix a false positive for `Style/RedundantSelfAssignmentBranch` when using instance variable, class variable, and global variable. ([@koic][]) diff --git a/lib/rubocop/cop/style/redundant_self_assignment_branch.rb b/lib/rubocop/cop/style/redundant_self_assignment_branch.rb index c9083cd31780..d8a9dd8c6703 100644 --- a/lib/rubocop/cop/style/redundant_self_assignment_branch.rb +++ b/lib/rubocop/cop/style/redundant_self_assignment_branch.rb @@ -5,6 +5,9 @@ module Cop module Style # This cop checks for places where conditional branch makes redundant self-assignment. # + # It only detects local variable because it may replace state of instance variable, + # class variable, and global variable that have state across methods with `nil`. + # # @example # # # bad @@ -45,10 +48,6 @@ def on_lvasgn(node) end end - alias on_ivasgn on_lvasgn - alias on_cvasgn on_lvasgn - alias on_gvasgn on_lvasgn - private def self_assign?(variable, branch) diff --git a/spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb b/spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb index 09e8955bc9f3..bc88cc7050e6 100644 --- a/spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb +++ b/spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb @@ -125,36 +125,21 @@ RUBY end - it 'registers and corrects an offense when self-assigning redundant else ternary branch for ivar' do - expect_offense(<<~RUBY) + it 'does not register an offense when self-assigning redundant else ternary branch for ivar' do + expect_no_offenses(<<~RUBY) @foo = condition ? @bar : @foo - ^^^^ Remove the self-assignment branch. - RUBY - - expect_correction(<<~RUBY) - @foo = @bar if condition RUBY end - it 'registers and corrects an offense when self-assigning redundant else ternary branch for cvar' do - expect_offense(<<~RUBY) + it 'does not register an offense when self-assigning redundant else ternary branch for cvar' do + expect_no_offenses(<<~RUBY) @@foo = condition ? @@bar : @@foo - ^^^^^ Remove the self-assignment branch. - RUBY - - expect_correction(<<~RUBY) - @@foo = @@bar if condition RUBY end - it 'registers and corrects an offense when self-assigning redundant else ternary branch for gvar' do - expect_offense(<<~RUBY) + it 'does not register an offense when self-assigning redundant else ternary branch for gvar' do + expect_no_offenses(<<~RUBY) $foo = condition ? $bar : $foo - ^^^^ Remove the self-assignment branch. - RUBY - - expect_correction(<<~RUBY) - $foo = $bar if condition RUBY end