首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FactoryGirl:避免为1模型单元测试创建多个模型实例

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

Stack Overflow用户
提问于 2017-02-28 20:46:47
回答 1查看 188关注 0票数 0

Rails 3.2.13,FactoryGirl,最小规格-rails.

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

有没有一种方法可以在FactoryGirl中定义不使用现有模型的关联?

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

目前,我有以下几点:

要求'test_helper‘

代码语言:javascript
复制
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)

代码语言:javascript
复制
# 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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-28 20:51:17

对于每一种关系,您仍然可以使用真实的模型,但是使用build_stubbed而不是build,它应该更快、更轻:

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42518431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档