I've run into a Fabrication issue and I'm not sure how best to go about solving it. I have three classes: Foo, Bar, and Linker. Foos have many Bars through Linker, and Bars have many Foos through Linker. Foos can exist without any Bars though, and vice versa. To make sure that nothing goes wonky with the associations, I have a validation on Linker that checks for the presence of a Foo and Bar (Linkers are only used to join a Foo and a Bar).
My problem is that I want to write a Fabricator that creates a Foo with associated Bars. Because of the order of validations, if I do:
Fabricator(:foo_with_bars, class_name: Foo) do
bars(count: 3) { Fabricate(:bar) }
end
This doesn't work, because Bars are created first, then Linkers, then Foo. Since at the time Linkers are validated, Foo hasn't been saved, the validation fails.
I can instead do this with a callback like so:
Fabricator(:foo_with_bars, class_name: Foo) do
after_create do |foo|
foo.bars = (1..3).map { Fabricate(:bar) }
end
end
This works with Fabricate, but if I use Fabricate.build the callback never gets called since we never use create.
My general question is: is there a pattern for this sort of thing in Fabrication, where an after_create callback is used if we're using Fabricate(), but a regular association setup is used if we're doing Fabricate.build()? I can always create helper methods that do this for me, but it would be nice if Fabrication had an elegant solution.