与 Factory Girl 工厂更新记录

发布于 2024-11-29 14:59:53 字数 541 浏览 3 评论 0原文

我使用 RSpec 和 Factory Girl 创建一条记录,该记录在创建时会在 after_create 中自动创建关联的“小时”记录。

但我想用非默认时间进行测试,最好是我在女工厂中定义的时间。这就是我想我想做的:

  before (:all) do
    @business = Factory(:business_one)
    # when that business is saved, a set of default hours is automatically saved as well
    # how would I now update the hours with fixtures?
    # so, ideally something like:
    @business.hours[0] << Factory(:day_one)
    @business.hours[1] << Factory(:day_two)
    ...etc...
  end

这是否可行,或者我是否需要以不同的方式处理这个问题?

Using RSpec and Factory Girl, I create a record that when created, has associated 'hours' records automatically created in after_create.

But I want to test with the non-default hours, preferably ones I define in factory girl factories. Here's what I'm thinking I'd like to do:

  before (:all) do
    @business = Factory(:business_one)
    # when that business is saved, a set of default hours is automatically saved as well
    # how would I now update the hours with fixtures?
    # so, ideally something like:
    @business.hours[0] << Factory(:day_one)
    @business.hours[1] << Factory(:day_two)
    ...etc...
  end

Is this doable somehow or do I need to approach this differently?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

溺孤伤于心 2024-12-06 14:59:53

为什么不创建一个替代工厂:

Factory.define :business_with_altnernate_hours, :parent => :business_one do
  after_create do |business|
    business.hours.clear
    Factory.create(:day_one, :business => business)
    Factory.create(:day_two, :business => business)
  end
end

Why not create an alternate factory:

Factory.define :business_with_altnernate_hours, :parent => :business_one do
  after_create do |business|
    business.hours.clear
    Factory.create(:day_one, :business => business)
    Factory.create(:day_two, :business => business)
  end
end
柒七 2024-12-06 14:59:53

您可以这样做:

@business = Factory(:business_one)

# clear associations so it's in a known state
@business.hours.clear

@business.hours << Factory(:day_one)
@business.hours << Factory(:day_two)

它们仍将按照您推入新关联的顺序插入和保存。

This is what you can do:

@business = Factory(:business_one)

# clear associations so it's in a known state
@business.hours.clear

@business.hours << Factory(:day_one)
@business.hours << Factory(:day_two)

They will still be inserted and saved in the order in which you push in the new association.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文