Rails 3.2.13,FactoryGirl,最小规格-rails.
我想为InvoicedItem模型定义一个工厂。此InvoicedItem属于(多态) :owner。这个owner可以是一个SpentItem。为了创建一个SpentItem,我需要创建其他几个记录(PricingGroup、PriceRatio、Supplier等)。这很快就变成了噩梦。
有没有一种方法可以在FactoryGirl中定义不使用现有模型的关联?
基本上,我不想为了测试SpentItem而实例化几个与InvoicedItem相关的模型。我只需要owner of InvoicedItem响应以下方法: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发布于 2017-02-28 20:51:17
对于每一种关系,您仍然可以使用真实的模型,但是使用build_stubbed而不是build,它应该更快、更轻:
https://robots.thoughtbot.com/use-factory-girls-build-stubbed-for-a-faster-test
https://stackoverflow.com/questions/42518431
复制相似问题