Skip to content

Commit

Permalink
Fix a false positive for FactoryBot/ConsistentParenthesesStyle when…
Browse files Browse the repository at this point in the history
… hash pinning

Fix: #84
  • Loading branch information
ydah committed Jan 1, 2024
1 parent d6a9e4a commit fa3e81f
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

- Fix a false positive for `FactoryBot/FactoryNameStyle` when namespaced models. ([@ydah])
- Add new `FactoryBot/ExcessiveCreateList` cop. ([@ddieulivol])
- Fix a false positive for `FactoryBot/ConsistentParenthesesStyle` when hash pinning. ([@ydah])

## 2.24.0 (2023-09-18)

Expand Down
12 changes: 12 additions & 0 deletions lib/rubocop/cop/factory_bot/consistent_parentheses_style.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ class ConsistentParenthesesStyle < ::RuboCop::Cop::Base
)
PATTERN

# @!method omit_hash_value?(node)
def_node_matcher :omit_hash_value?, <<~PATTERN
(send
#factory_call? %FACTORY_CALLS
{sym str send lvar}
(hash
<value_omission? ...>
)
)
PATTERN

def self.autocorrect_incompatible_with
[Style::MethodCallWithArgsParentheses]
end
Expand All @@ -97,6 +108,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|
Expand Down
42 changes: 42 additions & 0 deletions spec/rubocop/cop/factory_bot/consistent_parentheses_style_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,48 @@
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:)
create(:user, name:, client:)
RUBY
end

it 'does not register an offense when using `create` ' \
'with pinned hash argument and other unpinned args' do
expect_no_offenses(<<~RUBY)
create(:user, client:, name: 'foo')
create(:user, client: 'foo', name:)
RUBY
end

it 'registers an offense when using `create` ' \
'with unpinned hash argument' do
expect_offense(<<~RUBY)
create(:user, name: 'foo')
^^^^^^ Prefer method call without parentheses
RUBY

expect_correction(<<~RUBY)
create :user, name: 'foo'
RUBY
end

it 'registers an offense when using `create` ' \
'with method call has pinned hash argument' do
expect_offense(<<~RUBY)
create(:user, foo(name:))
^^^^^^ Prefer method call without parentheses
RUBY

expect_correction(<<~RUBY)
create :user, foo(name:)
RUBY
end
end
end

context 'when ExplicitOnly is false' do
Expand Down

0 comments on commit fa3e81f

Please sign in to comment.