Posted over 7 years ago. Visible to the public. Repeats.

Don't build randomness into your factories

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.

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

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

Instead do this:

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

The case against Faker

I even recommend to not use libraries like Faker Archive . 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:

Copy
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.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Henning Koch
Last edit:
22 days ago
by Tobias Kraze
Keywords:
blueprints, factory_girl, machinist
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more