Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Master (Unreleased)

- Fix a false positive for `FactoryBot/ConsistentParenthesesStyle` when using traits and omitting hash values. ([@thejonroberts])
- Fix false positives for `FactoryBot/AssociationStyle` with `strategy: :create` option. ([@ydakuka])

## 2.26.1 (2024-06-12)

Expand Down Expand Up @@ -117,3 +118,4 @@
[@walf443]: https://github.com/walf443
[@ybiquitous]: https://github.com/ybiquitous
[@ydah]: https://github.com/ydah
[@ydakuka]: https://github.com/ydakuka
7 changes: 7 additions & 0 deletions lib/rubocop/cop/factory_bot/association_style.rb
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ def on_send(node)
)
PATTERN

# @!method strategy_create_pair?(node)
def_node_matcher :strategy_create_pair?, <<~PATTERN
(pair (sym :strategy) (sym :create))
PATTERN

# @!method implicit_association?(node)
def_node_matcher :implicit_association?, <<~PATTERN
(send nil? !#non_implicit_association_method_name? ...)
Expand Down Expand Up @@ -234,6 +239,8 @@ def options_from_explicit(node)
return {} unless node.last_argument.hash_type?

node.last_argument.pairs.inject({}) do |options, pair|
next options if strategy_create_pair?(pair)

options.merge(pair.key.value => pair.value.source)
end
end
Expand Down
23 changes: 23 additions & 0 deletions spec/rubocop/cop/factory_bot/association_style_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,29 @@ def inspected_source_filename
end
end

context 'with `strategy: :create` option' do
it 'registers an offense' do
expect_offense(<<~RUBY)
factory :article do
association :user, strategy: :create
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use implicit style to define associations.
association :reviewer, factory: :user, strategy: :create
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use implicit style to define associations.
association :tag, :pop, strategy: :create
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use implicit style to define associations.
end
RUBY

expect_correction(<<~RUBY)
factory :article do
user
reviewer factory: %i[user]
tag factory: %i[tag pop]
end
RUBY
end
end

context 'when `association` is called in trait block ' \
'and column name is keyword' do
it 'does not register an offense' do
Expand Down
Loading