如何创建一个融合了另外两个记录的FactoryBot工厂?

发布于 2025-02-14 02:10:58 字数 468 浏览 0 评论 0 原文

我有一个对象,我们称其为过境者。

它不是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?!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

A君 2025-02-21 02:10:58

ThinkyBot最近写了a 博客文章主题和FactoryBot的Readme有一个关于创建非AR Ruby类的工厂。值得注意的是,该实现依赖于 initialize_with 使用自定义块实例化工厂,而不是调用 new 的默认行为,而没有任何假定为AR模型的参数。

在您的情况下,我想象一个 TressitProvider 出厂,看起来像:

factory :transit_provider do
  provider { create(:provider) }
  transit_service { create(:transit_service) }

  initialize_with { new(provider, transit_service) }
end

也很重要,请注意,创建永远不会适用于上述工厂,因为这试图实例化模型和坚持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 calling new 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:

factory :transit_provider do
  provider { create(:provider) }
  transit_service { create(:transit_service) }

  initialize_with { new(provider, transit_service) }
end

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 to build this factory instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文