Kostas
Kostas

Reputation: 8615

Creating a factory as a different class in Ruby with FactoryGirl

I have some ActiveRecord superclass Product and a subclass DiscountedProduct that share the same table and I have some factories for the superclass that I want to use with the subclass.

Factory(:product).class #=> Product

What I am trying to find is a shorthand for:

DiscountedProduct.create(Factory.build(:product).attributes)

NOTICE: I don't use Factory.attributes_for so that the needed associations get built.

Upvotes: 1

Views: 1238

Answers (1)

goldenlink
goldenlink

Reputation: 41

Well, seems factory_girl supports quite well the inheritance.

You can define your factory either way :

  • As a nested definition

    factory :product do
      name 'Product name'
    
      factory :discounted_product do
        discounted true
      end
    end
    
  • or as a linked definition

    factory :discounted_product :parent => :product do
      approved true
    end
    

Upvotes: 2

Related Questions