diff --git a/changelog/fix_a_false_positive_for_style_fetch_env_var_cop.md b/changelog/fix_a_false_positive_for_style_fetch_env_var_cop.md new file mode 100644 index 00000000000..632bd0b8c08 --- /dev/null +++ b/changelog/fix_a_false_positive_for_style_fetch_env_var_cop.md @@ -0,0 +1 @@ +* [#10581](https://github.com/rubocop/rubocop/issues/10581): Fix a false positive for `Style/FetchEnvVar` when comparing with `ENV['TERM']`. ([@koic][]) diff --git a/lib/rubocop/cop/style/fetch_env_var.rb b/lib/rubocop/cop/style/fetch_env_var.rb index 9ed2886883f..258ccb1c114 100644 --- a/lib/rubocop/cop/style/fetch_env_var.rb +++ b/lib/rubocop/cop/style/fetch_env_var.rb @@ -53,8 +53,9 @@ def allowed_var?(expression) def used_as_flag?(node) return false if node.root? + return true if node.parent.if_type? - node.parent.if_type? || (node.parent.send_type? && node.parent.prefix_bang?) + node.parent.send_type? && (node.parent.prefix_bang? || node.parent.comparison_method?) end # Check if the node is a receiver and receives a message with dot syntax. diff --git a/spec/rubocop/cop/style/fetch_env_var_spec.rb b/spec/rubocop/cop/style/fetch_env_var_spec.rb index be82c930898..8f98e7ae43e 100644 --- a/spec/rubocop/cop/style/fetch_env_var_spec.rb +++ b/spec/rubocop/cop/style/fetch_env_var_spec.rb @@ -49,15 +49,18 @@ end end - context 'when it is compared with other object' do - it 'registers an offense' do - expect_offense(<<~RUBY) + context 'when it is compared `==` with other object' do + it 'does not register an offense' do + expect_no_offenses(<<~RUBY) ENV['X'] == 1 - ^^^^^^^^ Use `ENV.fetch('X')` or `ENV.fetch('X', nil)` instead of `ENV['X']`. RUBY + end + end - expect_correction(<<~RUBY) - ENV.fetch('X', nil) == 1 + context 'when it is compared `!=` with other object' do + it 'does not register an offense' do + expect_no_offenses(<<~RUBY) + ENV['X'] != 1 RUBY end end