Use factories to create jumbo object graphs

The entire time I’ve been using FactoryBot, several years at this point, I’ve used it one factory at a time:

company = create(:company, name: "Acme, Inc.")
alice = create(:user, name: "Alice Smith")
posts = create_list(:post, 3, user: alice)

Do you see the mistake I make all the dang time? Spoiler alert, I forgot the company relation on Alice’s user, so she is either orphaned (unfortunate) or created on an entirely unrelated company. That’s gonna make my test fail in weird ways!

Lately, I’ve been trying something different: create the whole object graph I want to test on in one fell swoop:

company = create(
  :company,
  name: "Acme, Inc",
  user: build(
    :user, 
    name: "Alice Smith",
    posts: build_list(:post, 3)
  )
)

The entire intent of the test scenario is made clear right here. And, the error I so often make is solved structurally rather than by vigilance.

Granted, that’s pretty chunky and way more lines. I feel like it’s a worthy tradeoff!

When I need to reference the models created by my jumbo object graph, I use RSpec let and ActiveRecord finders with a mind towards consistently finding the right thing:

let(:company) do
  create(...) # the whole company bit from above
end
let(:alice) { company.users.find_by(name: "Alice Smith") }
let(:posts) { alice.posts }
Published

By Adam Keys

Telling a joke. Typing.