【问题标题】:Accessing a variable on another file in Rails在 Rails 中访问另一个文件上的变量
【发布时间】:2021-03-26 14:07:03
【问题描述】:

我有以下种子文件,可以创建需要测试的特定类型的动物:

animal_seeder.rb

# frozen_string_literal: true

animal1 = create(:animal, name:"id0_12", type:"fish,  score: 2 ...)
animal2 = create(:animal, name:"id0_123",type:"dog",  score: 121 ...)
animal3 = create(:animal, name:"id0_997",type:"cat",  score: 5 ...)

我现在遇到的问题是我还有另外 2 个名为 store_seeder.rb 的播种机和依赖于使用在 animal_seeder 中创建的动物变量的食物播种机。

例如。

create(
  :animal_store,
  timestamp: DateTime.now,
  version: 3,
  targets: {
    "food": {
      food.id=>{
        "animals": {  
            animal1.id =>{
              score:1231, 
              present: true, 
              .....
     }

我们正在寻求测试特定用例,因此我无法为动物变量随机创建变量。有没有一种方法可以创建动物并将它们用作其他种子的参考?

【问题讨论】:

  • 这是 FactoryBot 吗?以及哪个测试框架?
  • @Schwern 是的,我正在使用工厂机器人
  • animal_store 的结构有点搞笑。它真的是一家食品店,而且食品是为某些动物准备的吗?
  • @Schwern 是的,这可能不是最好的例子,尽管我想知道在概念上我是否可以这样做,因为我们的种子的其他实例需要专门制作的变量来测试数据

标签: ruby-on-rails ruby seeding


【解决方案1】:

首先,摆脱固定装置。正如您所发现的,它们很难维护。

相反,为您的特定测试创建所需的动物并将它们传递给商店。

let(:animals) {
  create_list(:animal, 3)
}
let(:animal_store) {
  create(:animal_store, animals: animals)
}

现在您知道animal_store 包含animals

将这些特定的动物添加到animal_store 似乎并不简单。您必须构建整个 Hash 结构和 Food 对象...不要用细节打扰测试作者,而是将动物作为 transient attribute 传递并在工厂中完成工作。

factory :animal_store do
  # Give them sensible defaults.
  transient do
    animals { create_list(:animal, num_target_animals) }
    num_animals { 3 }
    foods { create_list(:food, num_foods) }
    num_foods { 3 }
  end

  timestamp { DateTime.now }

  # targets is complex enough that it benefits from its own factory.
  # Pass the supplied animals and foods through.
  targets factory: :animal_store_targets, animals: animals, foods: foods
end

factory :animal_store_targets, class: Hash do
  transient do
    animals { create_list(:animal, num_target_animals) }
    num_animals { 3 }
    foods { create_list(:food, num_foods) }
    num_foods { 3 }
  end

  targets do
    # I'll leave building the targets Hash from animals and foods to you.
  end

  # Cheap trick to make a Hash with symbol keys.
  initialize_with do
    attributes
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2012-06-29
    相关资源
    最近更新 更多