3

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

FactoryGirl.define do
  factory :user do
  trait(:no_credits) { credits 0 }
  trait(:with_credits) { credits 300 }

How will you define this in Fabrication? I have gone through their website but couldn't find anything regarding this. Will appreciate your help

python
  • 4,403
  • 13
  • 56
  • 103

1 Answers1

2

Seems that your are looking for Fabricator inheritance, this is what the docs says:

You can inherit attributes from other fabricators by using the :from attribute.

Fabricator(:llc, from: :company) do
  type "LLC"
end

Setting the :from option will inherit the class and all the attributes from the named Fabricator.

You can also explicitly specify the class being fabricated with the :class_name parameter.

Fabricator(:llc, class_name: :company) do
  type "LLC"
end
Axxiss
  • 4,759
  • 4
  • 26
  • 45
  • Are you sure about inheritance? Because `trait` is more like defining custom attributes. In my example, the `user` will have `credits` 0. I don't think inheritance is the right approach. – python Mar 17 '16 at 16:06
  • You can define the defaults on the base class, each inherited class will override some of those default values. I think it will behave as you expect. Give it a try and tell me if it worked :) – Axxiss Mar 17 '16 at 16:09
  • In factory girls, we also have `after(:create)` that we can use with `trait`. Do you know anyway I can do something similar with fabrication? – python Mar 17 '16 at 16:26
  • Take a look to callbacks https://github.com/paulelliott/fabrication-site/blob/master/source/index.markdown#callbacks – Axxiss Mar 17 '16 at 17:52
  • `Traits` are not models so you cannot use `Fabricator` with them. I just realized this – python Mar 17 '16 at 21:38