如何让工厂只为 Rspec 中的所有测试创建一次数据

发布于 2025-01-13 15:50:02 字数 639 浏览 2 评论 0原文

这是我的代码的一个简化版本:

frozen_string_literal: true
RSpec.describe MyObject do
  let!(:my_object)  { create(:my_object, name: 'This Name') }
  let!(:my_ojbect_2) { create(:my_object_2, obj: my_object) }

  describe '#my_data' do
    subject { my_object.my_data }

    context 'when a' do
      ...
      ...

      it { is_expected.to eq expected_value }
    end

    context 'when b' do
      ...
      ...
      it { is_expected.to eq expected_value }
    end

    context 'when' do
      ...
      ...
      it { byebug }
    end
  end
end

当测试在 byebug 处停止时,我注意到 my_object 在数据库中创建了多次。有没有办法让 my_object 只创建一次?

Here is a little simplified version of my code:

frozen_string_literal: true
RSpec.describe MyObject do
  let!(:my_object)  { create(:my_object, name: 'This Name') }
  let!(:my_ojbect_2) { create(:my_object_2, obj: my_object) }

  describe '#my_data' do
    subject { my_object.my_data }

    context 'when a' do
      ...
      ...

      it { is_expected.to eq expected_value }
    end

    context 'when b' do
      ...
      ...
      it { is_expected.to eq expected_value }
    end

    context 'when' do
      ...
      ...
      it { byebug }
    end
  end
end

When the test stopped at the byebug, I noticed that my_object was created multiple times in the database. Is there a way to have my_object only create one time?

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

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

发布评论

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

评论(1

错爱 2025-01-20 15:50:02

如果测试对象的多个副本在测试之间持续存在,这会给您的测试带来巨大的问题,并且它们不可靠。

在两次测试之间你必须有一个干净的记录。有很多方法可以做到这一点,但工厂、固定装置、事务固定装置等可能会变得复杂。

我个人几乎总是最终使用数据库清理器。

看看数据库清理器

If multiple copies of test objects are persisting between tests this creates huge problems for your tests, and they cannot be relied on.

You have to have a clean slate between tests. There are a number of ways to do this, but it can get complicated with factories, fixtures, transactional fixtures, etc.

I personally almost always end up using a database cleaner.

Have a look at Database Cleaner

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