我有一个对象,我们称其为过境者。
它不是activerecord对象。它使用ActiveModel,但旨在从两个单独的表,一个提供商表和一个过渡表中汲取(或坚持)的数据。 (原因是:“公交提供商”的概念是由提供运输服务的提供商组成的概念)。
因此,这很好,除非我尝试为TransitProvider构建工厂(使用FactoryBot)。
它没有表,所以我不能“创建”一个。相反,我需要实际创建基础提供商和转运服务。
但是我不知道该如何在FactoryBot中做到这一点。
我希望能够做类似的事情:
let(:transit_provider) { create(:transit_provider, name: "Some Name") }
“封面下”实际上创建了提供商和转移服务,然后用两者中的数据填充了ActiveModeL TransitProvider。
帮助?!
I have an object, let's call it a TransitProvider.
It isn't an ActiveRecord object. It uses ActiveModel but it's designed to pull (or persist) it's data from two separate tables, a Provider table and a TransitService table. (reason being: the concept of "Transit Provider" is a concept that is made up of a Provider that offers a Transit Service).
So this is working well, except when I try to build a Factory (using FactoryBot) for the TransitProvider.
It doesn't have a table, so I can't "create" one. Instead, I'd need to actually create the underlying Provider and TransitService.
But I don't know how to do that in FactoryBot.
I want to be able to do stuff like:
let(:transit_provider) { create(:transit_provider, name: "Some Name") }
and have it "under the covers" actually create the Provider and the TransitService and then populate the ActiveModel TransitProvider with data from both.
Help?!
发布评论
评论(1)
ThinkyBot最近写了a 博客文章主题和FactoryBot的Readme有一个关于创建非AR Ruby类的工厂。值得注意的是,该实现依赖于
initialize_with
使用自定义块实例化工厂,而不是调用new
的默认行为,而没有任何假定为AR模型的参数。在您的情况下,我想象一个
TressitProvider
出厂,看起来像:也很重要,请注意,
创建
永远不会适用于上述工厂,因为这试图实例化模型和坚持DB中的记录。您需要构建
这个工厂。Thoughtbot recently wrote a blog post on this subject, and FactoryBot's README has a section on creating factories for non-AR Ruby classes. Notably, the implementation relies on
initialize_with
to instantiate the factory using a custom block, rather than the default behavior of callingnew
without any arguments on what is assumed to be an AR model.In your scenario, I would imagine a
TransitProvider
factory that looks something like:Also important to note that
create
will never work for the above factory since that attempts to instantiate a model and persist a record in the DB. You'll want tobuild
this factory instead.