stephencelis

Miniskirt: factory_girl, relaxed

, Chicago

Living on the edge isn’t easy. You continuously risk that everything you rely on stops working.

Et tu, factory_girl?

The fix was easy enough1, but I started realized that I only really used a small fraction of what was under the hood. I took a page out of Ryan Davisbook, reordered the words, and wrote Miniskirt to complement minitest.

Miniskirt is factory_girl, relaxed. It’s the essential, with some flare:

  • Blocks are avoidable with Ruby 1.9 string interpolation. Avoid blocks if you can. Your models should handle their own logic.
    f.email '%{first_name}.%{last_name}@example.com' # ...not...
    f.email { |u| "#{u.first_name}.#{u.last_name}@example.com" }
    
  • Sequences are simpler (why bother with blocks?):
    f.email 'person%d@example.com' # ...instead of...
    f.sequence(:email) { |n| "person#{n}@example.com" }
    

What’s missing?

Factory.attributes_for :model.
Call Factory.build(:model).attributes, instead.
Factory.stub.
Stub your models like you stub everything else.
Factory#association.
Almost as short, and explicit: f.user { Factory :user }.
Factory#callback.
I can’t think of a callback that should be on a factory but not the model.

Here she is. All of her.

Not bad for under 30 LOC.

Miniskirt isn't for everyone. The slightly more conservative, more backwards-compatible Minidress may suit you better. Or maybe factory_girl, with all her bells and whistles, fits you just fine.2

Whatever you choose, though, remember: write less, and write better.


1 Up and running:

# test/test_helper.rb
Rails::Application.configuration.class_eval { alias configuration config }
require "factory_girl" # Now she loads just fine...
require "factories"    # ...and the rest needs to load explicitly.

2 I like factory_girl, and may find myself returning to her when my platform is a bit more stable, especially if she picks up some of these interpolative tricks.

Comments powered by Disqus.

Otherwise: