【问题标题】:How to have a factory in multiple files如何在多个文件中拥有一个工厂
【发布时间】:2022-04-19 00:18:28
【问题描述】:

我有一个模型被多个库使用,每个库都以不同的方法使用它。

目前我制作了一个工厂文件,其中包含多个子工厂。我的每个库都有一个工厂,因为每个库都需要我的基本模型的不同配置。

我的问题是我的工厂文件太长了,超过 400 行,我想把它分成多个文件,每个库一个。

现在我有这样的东西

# Master file
FactoryBot.define do
  factory :my_model do
    # Some things
    factory :lib_1_test_unit do
      # Some other things
    end
    factory :lib_2_test_unit do
      # Some other things
    end
  end
end

我试图这样定义它:

# New master file
FactoryBot.define do
  factory :my_model do
    # Some things
  end
end
# Subfile 1
  FactoryBot.define do
    factory :lib_1_test_unit do
      # Some other things
    end
  end

但我得到了那个错误:

未初始化的常量 Lib1TestUnit

如果我用 factory :my_model 包装我的子文件 1,我会收到另一个错误,因为我无法定义它两次。

我也尝试将子文件包含到主文件中,但效果更差

有没有办法实现我想做的事情?或者我一直走错路,也许有更好的做法或其他方法可以将同一个对象测试到不同的库中?

【问题讨论】:

    标签: ruby-on-rails ruby rspec factory-bot


    【解决方案1】:

    这不是你的问题的完整解决方案,更像是一个评论。

    也许你错过了子文件 1 中的“do”。

    你有: factory :lib_1_test_unit 你需要: factory :lib_1_test_unit do

    【讨论】:

    • 感谢您的评论,实际上我在这个例子中忘记了它们,它们在真实代码中。我编辑了代码。
    【解决方案2】:

    似乎没有这方面的功能,也不需要

    参考:https://github.com/thoughtbot/guides/issues/352

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 2021-09-30
      • 2020-05-07
      • 2020-05-10
      • 2016-03-27
      相关资源
      最近更新 更多