Backend Pattern Factory - department-of-veterans-affairs/caseflow GitHub Wiki

[Pattern] Factory

Description

Factories are used to generate fake data for testing.

Caseflow uses Factory Bot to implement our factory classes.

Location

  • spec/factories/

Best Practices

  • Default factories should only contain the minimum amount of attributes required. Create new factories for different scenarios. If some attribute or association doesn't apply globally, don't set it on the default factory.

  • Don't create associations with a block in factories. Example:

    factory :task do
      appeal { create(:legacy_appeal, vacols_case: create(:case)) }
    end

    Instead, use the documented way of setting up associations:

    # This will use the `appeal` factory
    factory :task do
      appeal
    end

    or if you want a different class and attributes for the association:

    factory :legacy_task do
      association :appeal, factory: :legacy_appeal
    end

    The problem with using create for associations in factories is it prevents the parent factory from being stubbed. For example, if we don't need to use the DB, we can use build_stubbed(:task), but if the task factory defines the appeal association by creating a new appeal, calling build_stubbed(:task) will write to the DB. We can get around that by specifying a stubbed appeal: build_stubbed(:task, appeal: build_stubbed(:appeal) but that is more verbose than necessary. The default should be to easily allow stubbing factories along with their associations.

Tradeoffs

N/A

Resources

Examples in Caseflow

Additional Reading

Related Patterns

Pattern Description
Test Used in tests
⚠️ **GitHub.com Fallback** ⚠️