eeeeeean eeeeeean - 8 months ago 36
Ruby Question

How do I return an existing instance from factory_girl create?

I have two factories:

factory :foo
factory :bar

A Foo has_one Bar.

foo.rb has an after_create callback to create a Bar object. Currently, I'm able to get what I need like this, but it's a minimal example:

let(:bar) { create(:foo).bar }

I'd like to get the Bar object more directly, like this (which doesn't work)...

factory :bar_from_foo_callback do
to_create { create(:foo).bar }

...and then just call
to get the Bar I need. I thought that to_create looked like a good bet, but it's giving me:

undefined method `bar' for

Is there a way I can define a factory so that it doesn't create, it just calls another factory and uses the callback?


This seems to work, although I haven't tested it extensively:

factory :bar do
  initialize_with { create(:foo).bar }

Note that factory_girl calls save! on the instance when you create(:bar), but in this case it does nothing because the Bar was already saved while creating the Foo.