2017-03-09 82 views
1

我有一个FactoryGirl模型类。在这个模型中,我定义了一些特征。在一些特质中,我不希望FactoryGirl回调调用,但我不知道如何。例如,下面是我的代码:工厂女孩:想要防止一些性状的工厂女孩​​回调

FactoryGirl.define do 
    factory :product do 
    sequence(:promotion_item_code) { |n| "promotion_item_code#{n}" } 

    after :create do |product| 
     FactoryGirl.create_list :product_details, 1, :product => product 
    end 

    trait :special_product do 
     # do some thing 
     # and don't want to run FactoryGirl callback 
    end 
end 

在这段代码中,我不想:special_product特质调用after :create。我不知道该怎么做。

@Edit:我想这样做的原因是因为有时我想从父 - >子生成数据。但有时候我想反过来从孩子到父母产生。所以当我从孩子 - >父母去时,会调用父母的回调函数,这样孩子就会创建两次。这不是我想要的。

@编辑2:我的问题是阻止从FactoryGirl,而不是从ActiveRecord模型回调。

感谢

+0

的[跳过对工厂女孩和Rspec的回调(http://stackoverflow.com/questions/8751175/skip-callbacks-on-factory-girl-and-rspec) –

+1

@WesFoster都能跟得上可能的复制。请仔细阅读答案和问题。您的文章是关于跳过ActiveRecord回调。 –

回答

2

您可以使用transient attributes来实现这一目标。

像:

factory :product do 
    transient do 
    create_products true 
    end 

    sequence(:promotion_item_code) { |n| "promotion_item_code#{n}" } 

    after :create do |product, evaluator| 
    FactoryGirl.create_list(:product_details, 1, :product => product) if evaluator.create_products 
    end 

    trait :special_product do 
    # do some thing 
    # and don't want to run FactoryGirl callback 
    end 
end 

但我认为,更好的方法来模拟这种问题是定义一个trait为“基本情况”或有多个工厂。

+0

不是。问题仍然存在,因为始终设置了“create_products”。 –

+0

当你不想创建产品时,你应该通过false来传递'create_products'。 – Fredius

+0

我正在使用关联。我不知道传递数据的方式。这里是我的代码:'association:product,:factory => [:product,:special_product]'thanks –

0

,作为一个has_many relationship在工厂女孩文档描述,您可以使用相同的方法:

factory :product_detail do 
    product 
    #... other product_detail attributes 
end 

factory :product do 
    sequence(:promotion_item_code) { |n| "promotion_item_code#{n}" } 

    factory :product_with_details do 
    transient do 
     details_count 1 # to match your example. 
    end 

    after(:create) do |product, evaluator| 
     create_list(:product_detail, evaluator.details_count, product: product) 
    end 
    end 

    trait :special_product do 
    # do some thing 
    # and don't want to run FactoryGirl callback 
    end 
end 

这可以让你的父母与生成数据>孩子:

create(:product_with_details)     # creates a product with one detail. 
create(:product_with_details, details_count: 5) # if you want more than 1 detail. 

.. 。对于特殊产品只需

# does not create any product_details. 
create(:product) 
create(:product, :special_product) 

要为儿童生成 - > paren吨

create(:product_detail)