eeeeeean eeeeeean - 5 months ago 26
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 }
end


...and then just call
create(:bar_from_foo_callback)
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
#<FactoryGirl::Declaration::Static:0x007fb85e3d79d0>


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

Answer

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

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

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.