Fabrication gem: how to pass custom values to init_with()?

1.1k views Asked by At

The Fabrication gem allows us to pass custom arguments to the constructor of the class we are fabricating:

on_init { init_with('something', true) }

But how can I pass custom values for init_with in object generation time?

For the object fields, I can do like the following, but is there a way to pass the values to init_with?

Fabricate(:foobar, attr1: 'something', attr2: true)
2

There are 2 answers

0
phoet On BEST ANSWER

As far as I can see, this is not possible.

  def build_instance_with_init_callback(callback)
    self._instance = _klass.new(*callback.call)
    set_attributes
  end

You are stuck with what you used in the fabricator definition.

1
Paul Elliott On

You can use the block syntax at Fabricate time just like you would when you define the Fabricator.

Fabricate(:foobar, attr1: 'something', attr2: true) do
  on_init { init_with('another', 'thing') }
end