FactoryBot Tips

“Base” Factory

  • Provide the minimum values necessary to be able to save a valid instance.
  • Optional fields or fields with default values are not generally provided.
  • belongs_to associations should be provided assuming they are required (the default in Rails)
  • If has_one, has_many or has_and_belongs_to_many records are required for your object to function you may need to populate those, but you should try to avoid your object having that sort of dependency.

Random Values

Locate Important Values in Tests

it 'returns first and last name combined' do
user = create :user, first_name: 'Jane', last_name: 'Doe'
expect( user.full_name ).to eq 'Jane Doe'

Avoid Factory Proliferation

  • It keeps your factories more manageable
  • It makes it clear just by looking at the test what you are doing without having to go look up what admin_user actually means.




Software Developer. Primary love is Rails.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Eric Anderson

Eric Anderson

Software Developer. Primary love is Rails.

More from Medium

The Unseen Fury of Debugging

Codiga: 2021 in Review

Develop a Sense of Code.

The Road to Clean Code