【问题标题】:Updating records with Factory Girl factory用 Factory Girl factory 更新记录
【发布时间】:2011-08-11 15:58:18
【问题描述】:

使用 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

这是可行的还是我需要以不同的方式解决这个问题?

【问题讨论】:

    标签: ruby-on-rails rspec factory-bot


    【解决方案1】:

    为什么不创建一个备用工厂:

    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
    

    【讨论】:

      【解决方案2】:

      这是你可以做的:

      @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)
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多