Skip to content

Add new cop rule RSpec/FactoryBot/LocalStaticAssignment

What does this MR do and why?

Flag local assignments during factory "load time". This leads to static data definitions.

Move these definitions into attribute block or transient block to ensure that the data is evaluated during "runtime" and remains dynamic.

Example:

  # bad
  factory :foo do
    random = rand(23)
    baz { "baz-#{random}" }

    trait :a_trait do
      random = rand(23)
      baz { "baz-#{random}" }
    end

    transient do
      random = rand(23)
      baz { "baz-#{random}" }
    end
  end

  # good
  factory :foo do
    baz { "baz-#{random}" }

    trait :a_trait do
      baz { "baz-#{random}" }
    end

    transient do
      random { rand(23) }
    end
  end

Refs #409930 (comment 1385037311)

Real world examples

Offenses

See 🔴 https://gitlab.com/gitlab-org/gitlab/-/jobs/4258791892

spec/factories/design_management/designs.rb:29:5: C: RSpec/FactoryBot/StaticAssignment: Prefer dynamic definitions in factories.
    create_versions = ->(design, evaluator, commit_version) do ...
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This offense seems like a legit use case so it's fine to disable the cop inline.

MR acceptance checklist

This checklist encourages us to confirm any changes have been analyzed to reduce risks in quality, performance, reliability, security, and maintainability.

Edited by Peter Leitzen

Merge request reports

Loading