gpt4 book ai didi

ruby-on-rails - 工厂女孩 : want to prevent factory girl callbacks for some traits

转载 作者:数据小太阳 更新时间:2023-10-29 08:58:30 26 4
gpt4 key购买 nike

我有一个模型类的 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: 我之所以这样做是因为有时我想从父级 -> 子级生成数据。但有时我希望反之亦然,从 child 到 parent 。所以当我从 child -> parent 那里去时, parent 的回调被调用所以 child 被创建了两次。这不是我想要的。

@Edit 2:我的问题是防止来自 FactoryGirl 的回调,而不是来自 ActiveRecord 模型的回调。

谢谢

最佳答案

您可以使用 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 或拥有多个工厂。

关于ruby-on-rails - 工厂女孩 : want to prevent factory girl callbacks for some traits,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42696577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com