From dccdc2a859eeca7d975ba13a1c217f57ad7f418b Mon Sep 17 00:00:00 2001 From: ydah <13041216+ydah@users.noreply.github.com> Date: Thu, 16 Nov 2023 18:54:17 +0900 Subject: [PATCH] Fix a false positive for `FactoryBot/ConsistentParenthesesStyle` when hash pinning Fix: https://github.com/rubocop/rubocop-factory_bot/issues/84 --- CHANGELOG.md | 3 ++- .../cop/factory_bot/consistent_parentheses_style.rb | 10 ++++++++++ .../factory_bot/consistent_parentheses_style_spec.rb | 9 +++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a5b4bbaa..ac58c721 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,9 @@ ## Master (Unreleased) -- Fix a false positive for `FactoryBot/FactoryNameStyle` when namespaced models. ([@ydah]) - Add new `FactoryBot/ExcessiveCreateList` cop. ([@ddieulivol]) +- Fix a false positive for `FactoryBot/FactoryNameStyle` when namespaced models. ([@ydah]) +- Fix a false positive for `FactoryBot/ConsistentParenthesesStyle` when hash pinning. ([@ydah]) ## 2.24.0 (2023-09-18) diff --git a/lib/rubocop/cop/factory_bot/consistent_parentheses_style.rb b/lib/rubocop/cop/factory_bot/consistent_parentheses_style.rb index fd86f441..73f86175 100644 --- a/lib/rubocop/cop/factory_bot/consistent_parentheses_style.rb +++ b/lib/rubocop/cop/factory_bot/consistent_parentheses_style.rb @@ -75,6 +75,11 @@ class ConsistentParenthesesStyle < ::RuboCop::Cop::Base ) PATTERN + # @!method omit_hash_value?(node) + def_node_search :omit_hash_value?, <<~PATTERN + (hash #value_omission?) + PATTERN + def self.autocorrect_incompatible_with [Style::MethodCallWithArgsParentheses] end @@ -97,6 +102,7 @@ def register_offense(node) def register_offense_with_parentheses(node) return if style == :require_parentheses || !node.parenthesized? return unless same_line?(node, node.first_argument) + return if omit_hash_value?(node) add_offense(node.loc.selector, message: MSG_OMIT_PARENS) do |corrector| @@ -123,6 +129,10 @@ def remove_parentheses(corrector, node) corrector.replace(node.location.begin, ' ') corrector.remove(node.location.end) end + + def value_omission?(node) + node.value_omission? + end end end end diff --git a/spec/rubocop/cop/factory_bot/consistent_parentheses_style_spec.rb b/spec/rubocop/cop/factory_bot/consistent_parentheses_style_spec.rb index 97827dd9..9cb9f9cf 100644 --- a/spec/rubocop/cop/factory_bot/consistent_parentheses_style_spec.rb +++ b/spec/rubocop/cop/factory_bot/consistent_parentheses_style_spec.rb @@ -401,6 +401,15 @@ generate(:foo, :bar) RUBY end + + context 'when TargetRubyVersion >= 3.1', :ruby31 do + it 'does not register an offense when using `create` ' \ + 'with pinned hash argument' do + expect_no_offenses(<<~RUBY) + create(:user, name:) + RUBY + end + end end context 'when ExplicitOnly is false' do