Read more

Don't build randomness into your factories

Henning Koch
February 24, 2014Software engineer at makandra GmbH

Tests are about 100% control over UI interaction and your test scenario. Randomness makes writing tests hard. You will also push tests that are green for you today, but red for a colleague tomorrow.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

That said, please don't do something like this:

Factory(:document) do |document|
  document.category { ['foo', 'bar', 'baz'].sample }
end

Instead do this:

Factory(:document) do |document|
  document.category 'foo'
end

The case against Faker

I even recommend to not use libraries like Faker Show archive.org snapshot . Faker makes awesome sample data, but at the risk of adding random strings to your screen. When your factory requires unique values for something, prefer numbering fixed strings intead:

FactoryBot.define do
  sequence(:first_name)   { |i| "First#{i}" }
  sequence(:last_name)    { |i| "Last#{i}" }
  sequence(:company_name) { |i| "Company #{i}" }
end

This creates ugly sample data like "First3 Last3", but e.g. doesn't make tests pass when they shouldn't.

Posted by Henning Koch to makandra dev (2014-02-24 12:31)