diff --git a/changelog/fix_an_error_for_style_case_like_if.md b/changelog/fix_an_error_for_style_case_like_if.md new file mode 100644 index 000000000000..364a285ff35a --- /dev/null +++ b/changelog/fix_an_error_for_style_case_like_if.md @@ -0,0 +1 @@ +* [#12690](https://github.com/rubocop/rubocop/issues/12690): Fix an error for `Style/CaseLikeIf` when using `==` with literal and using ternary operator. ([@koic][]) diff --git a/lib/rubocop/cop/style/case_like_if.rb b/lib/rubocop/cop/style/case_like_if.rb index 164cee902f0b..76ad79114119 100644 --- a/lib/rubocop/cop/style/case_like_if.rb +++ b/lib/rubocop/cop/style/case_like_if.rb @@ -230,7 +230,7 @@ def condition_from_binary_op(lhs, rhs, target) def branch_conditions(node) conditions = [] - while node&.if_type? + while node&.if_type? && !node.ternary? conditions << node.condition node = node.else_branch end diff --git a/spec/rubocop/cop/style/case_like_if_spec.rb b/spec/rubocop/cop/style/case_like_if_spec.rb index 651193b8a0e2..bf05818af26d 100644 --- a/spec/rubocop/cop/style/case_like_if_spec.rb +++ b/spec/rubocop/cop/style/case_like_if_spec.rb @@ -59,6 +59,26 @@ RUBY end + it 'registers an offense when using `==` with literal and using ternary operator' do + expect_offense(<<~RUBY) + if foo == 1 + ^^^^^^^^^^^ Convert `if-elsif` to `case-when`. + elsif foo == 2 + else + foo == 3 ? bar : baz + end + RUBY + + expect_correction(<<~RUBY) + case foo + when 1 + when 2 + else + foo == 3 ? bar : baz + end + RUBY + end + it 'does not register an offense when using `==` with method call with arguments' do expect_no_offenses(<<~RUBY) if x == foo(1)