Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cop idea: restrict defining global factorybot traits #4

Open
t3h2mas opened this issue Dec 5, 2022 · 3 comments
Open

Cop idea: restrict defining global factorybot traits #4

t3h2mas opened this issue Dec 5, 2022 · 3 comments
Labels

Comments

@t3h2mas
Copy link

t3h2mas commented Dec 5, 2022

Factory bot allows for traits to be defined outside of a factory definition. This introduces the risk of collisions in as the tests grow in a codebase.

Example:

FactoryBot.define do
  factory :user do
    first_name { "John" }
    last_name  { "Doe" }
    admin { false }
  end

  trait :admin do
    admin { true }
  end
end

Works in a test

let(:user) { create(:user, :admin) }

Could a cop flag global trait definitions?

@pirj
Copy link
Member

pirj commented Dec 5, 2022

This says:

Traits allow you to group attributes together and then apply them to any factory.

And the reason for the very existence suggests that global traits have a reason to exist outside of factories.

But I agree with you that if a trait is meant to be used in several factories, it would make sense to at least define it in a separate file.

Are you certain that FactoryBot wouldn't/shouldn't warn about this?
It would be quite hard to tell if e.g. an :admin trait is defined in both spec/factories/common_traits.rb and spec/factories/admin.rb with static analysis.

@t3h2mas
Copy link
Author

t3h2mas commented Dec 29, 2022

It looks like factory bot does raise a FactoryBot::DuplicateDefinitionError. In our case, traits were added to the global scope unintentionally. I was hoping a cop could make global factories explicit.

it would make sense to at least define it in a separate file

This makes sense to me. Thoughts on a "global traits shouldn't be defined in the same file as factories" type of cop?

If this doesn't seem generally valuable, feel free to close @pirj

@pirj
Copy link
Member

pirj commented Dec 29, 2022

Thoughts on a "global traits shouldn't be defined in the same file as factories" type of cop?

Makes sense to me 👍

@ydah ydah transferred this issue from rubocop/rubocop-rspec May 6, 2023
@ydah ydah added the cop label May 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants