ruby-on-railstestingfactory-botfabrication-gem

How to write factory_girl create command using fabrication in rails


I am learning how to use fabrication in Rails and we have decided to replace all our factory_girl code with fabrication.

Suppose we have this code in factory_girl, how will I rewrite the whole thing using fabrication?

FactoryGirl.create(
  :payment,
  user: user_ny,
  amount: -4000,
  booking: booking,
  payable: payable]
)

Is this the correct code using Fabrication ? I am new to rails framework and will appreciate your help.

Fabricator(:payment) do
  name { user_ny }
  amount -4000
  booking { booking }
  payable { payable }
end

Solution

  • Fabrication's equivalent to FactoryGirl.create(:payment) is Fabricate(:payment).

    It looks like booking and payable are other fabricators so you could write it like this:

    Fabricate(:payment, name: user_ny) do
      amount -4000
      booking
      payable
    end
    

    If you declare a relationship without a "value" it performs a default expansion and generates whatever the fabricator of the same name defines and sets it on the object.

    In the case of user_ny above, the easiest way to use a local variable when fabricating is to pass it in as a parameter. You can mix and match however you want between the parameters and block syntax, although parameters will take precedence.