gpt4 book ai didi

ruby-on-rails - FactoryGirl : Creating dynamic factories with parameters?

转载 作者:行者123 更新时间:2023-12-04 22:32:40 25 4
gpt4 key购买 nike

我有三个工厂要烘干。它们看起来像这样:

factory :sequenced_stamps_by_years, class: Stamp do
...
sequence(:day_date) { |n| n.years.ago }
end

factory :sequenced_stamps_by_months, class: Stamp do
...
sequence(:day_date) { |n| n.months.ago }
end

factory :sequenced_stamps_by_weeks, class: Stamp do
...
sequence(:day_date) { |n| n.weeks.ago }
end

我怎样才能把它弄干?我希望能够像这样创建它们:
FactoryGirl.create_list(:sequenced_stamps_by_x, 4, x: "weeks") ## <- So that i can decide whether I want weeks, days, years, or months ago.

这可能吗?

最佳答案

如果您不喜欢继承方法,则还有一种使用参数的替代方法。基本上:

factory :stamps do
ignore do
interval :years # possible values => :years, :months, :weeks
end

sequence(:date_date) { |n| n.send(interval).ago }

# rest of attributes here
end

现在你可以这样做:
FactoryGirl.create(:stamps, :interval => :months)

或者
FactoryGirl.create(:stamps)

默认为年。

您可以在 Factory Girl transient attributes 中找到所有这些

关于ruby-on-rails - FactoryGirl : Creating dynamic factories with parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16384935/

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