Rails 3.2.13,Factory Girl,Minitest最划线。
我想为InvoicedItem
型号定义工厂。此InvoicedItem
属于(多态):owner
。此owner
可以是SpentItem
。为了创建SpentItem
,我需要创建其他几个记录(PricingGroup
,PriceRatio
,Supplier
等),这很快就变成了一场噩梦。
是否有一种方法可以定义不使用现有模型的FactoryGirl中的关联?
基本上,我不想将几个相关模型实例化来测试InvoicedItem
。我只需要InvoicedItem的owner
响应以下方法:name_for_invoice
和bill_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
您仍然可以使用每种关系的真实模型,但使用build_stubbed
而不是build
,该CC_20应该更快且重量更轻:
https://robots.thoughtbot.com/use-factory-girls-build-pubbed-for-a-faster-test