Skip to content

RSpec: Flag use of `create` in certain spec types

Problem

In https://docs.gitlab.com/ee/development/testing_guide/best_practices.html#optimize-factory-usage we encourage the use of build_stubbed instead of create to avoid expensive SQL queries which make spec run slowly.

Certain spec types are not changing any state in the database and are just presenting/rendering passed models.

Those types are:

  • Presenters - spec/presenters
  • Serializers - spec/serializers
  • View Helpers - spec/helpers
  • Views - spec/views
  • View Components - spec/components
  • Mailers - spec/mailers

Using FactoryBot.create is slow and also (mostly - see Risks) not necessary for those type of specs.

Proposed solution

Discourage the use of create and suggest build_stubbed instead for these type of specs using a 👮 rule.

With this approach there's potential to shave off ~2600 s or 43 minutes from CI. It also improves overall developer experience when running these specs locally.

See the investigation in !98000.

Risks

Converting from create to build_stubbed is a mechanical task and should be doable in most cases, however:

  • Some factories are NOT capable to be used with build_stubbed
    • For example, they use before/after :create only
  • Some code actually modify passed model and saving changed state to the database
    • This could be accidental or by purpose

In these cases we must disable this 👮 rule and follow-up.