Yup. overlooked it in the documentation.
You can define them in your Fabricators as a block that optionally receives the object being fabricated and a hash of any transient attributes defined. As with anything that works in the Fabricator, you can also define them when you call Fabricate and they will work just like you’d expect. The callbacks are also stackable, meaning that you can declare multiple of the same type in a fabricator and they will not be clobbered when you inherit another fabricator.
Fabricator(:place) do
before_validation { |place, transients| place.geolocate! }
after_create { |place, transients| Fabricate(:restaurant, place: place) }
end
Also, in my case, I needed to use the after_save callback. I was able set the current_bar
on my foo
object inside the fabricator, but once in the spec, the current_bar
was still nil
. The update
method isn't available inside after_create (I'm new to ruby so I'm not sure why), but it is available inside after_save. Calling update got me going.
Fabricator(:foo) do
transient :current_bar_data
after_save { |foo, transients|
bar = Fabricate( :bar, foo: foo, bar_data: transients[ :current_bar_data ] )
foo.update( current_bar: bar )
}
current_bar nil
end
Now I can fabricate a foo
complete with current_bar
for my specs:
let!( :some_foo ) { Fabricate( :foo, current_bar_data: "some bar data" ) }