2017-03-09 81 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)