FactoryGirl:避免为单模型单元测试创​​建多个模型实例

时间:2017-02-28 20:46:47

标签: ruby-on-rails unit-testing factory-bot

Rails 3.2.13,FactoryGirl,minitest-spec-rails。

我想为InvoicedItem模型定义工厂。此InvoicedItem属于(多态):owner。此owner可以是SpentItem。为了创建SpentItem,我需要创建其他几条记录(PricingGroupPriceRatioSupplier等等。)这很快就会变成一场噩梦。

有没有办法在FactoryGirl中定义一个不使用现有模型的关联?

基本上,我不想实例化几个SpentItem相关模型来测试InvoicedItem。我只需要InvoicedItem的owner响应以下方法:name_for_invoicebill_price_for_invoice

目前,我有这个:

要求'test_helper'

class FakeInvoicedItemOwner
  attr_accessor :name_for_invoice, :bill_price_for_invoice
end

FactoryGirl.define do
  factory 'FakeInvoicedItemOwner' do
    name_for_invoice { 'Fake Name' }
    bill_price_for_invoice { 12.0 }
  end

  factory 'Invoicing::InvoicedItem' do
    association :invoice, factory: 'Invoicing::Invoice'
    owner { FactoryGirl.build('FakeInvoicedItemOwner') }
    name { 'FG name' }
    billed_price { 1.0 }
  end
end

我总是遇到与持久性相关的错误:undefined method 'primary_key' for FakeInvoicedItemOwner:Class

因为FactoryGirl试图保留这个FakeInvoicedItemOwner实例,但我试图避免这种情况。有没有办法告诉FactoryGirl使用假对象而不是给真正的模型工厂?

编辑:解决方案

(命名错误,Plus::SpentItemStub应该是Invoicing::Stubs::SpentItem

# class inheriting from an invoice-able item
# redefines the methods used for Invoicing
class Plus::SpentItemStub < Plus::SpentItem
  def name_for_invoice
    'fake name for invoicing'
  end
end

FactoryGirl.define do
  # factory for my fake model above
  factory 'Plus::SpentItemStub' do
  end

  factory 'Invoicing::InvoicedItem' do
    # relation owner using a stubbed instance of my fake model
    owner { FactoryGirl.build_stubbed('Plus::SpentItemStub') }
    # ...
  end
end

1 个答案:

答案 0 :(得分:1)

您仍然可以使用每个关系的真实模型,但使用build_stubbed而不是build,这应该更快更轻:

https://robots.thoughtbot.com/use-factory-girls-build-stubbed-for-a-faster-test