【问题标题】:Singleton factories in factory_girl/machinist?factory_girl/机械师中的单身工厂?
【发布时间】:2011-05-18 02:23:53
【问题描述】:

工厂女孩/机械师工厂中是否有一些配置强制它在测试用例期间只创建一次具有相同工厂名称的对象并始终返回相同的实例?我知道,我可以这样做:

def singleton name
    @@singletons ||= {}
    @@singletons[name] ||= Factory name
end
...
Factory.define :my_model do |m|
   m.singleton_model { singleton :singleton_model }
end

但也许有更好的方法。

【问题讨论】:

    标签: singleton factory-bot machinist


    【解决方案1】:

    不确定这是否对您有用。

    通过此设置,您可以使用工厂“singleton_product”创建 n 个产品。所有这些产品都将具有相同的平台(即平台“FooBar”)。

    factory :platform do
      name 'Test Platform'
    end
    
    factory :product do
      name 'Test Product'
      platform
    
      trait :singleton do
        platform{
          search = Platform.find_by_name('FooBar')
          if search.blank?
            FactoryGirl.create(:platform, :name => 'FooBar')
          else
            search
          end
        }
      end
    
      factory :singleton_product, :traits => [:singleton]
    end
    

    您仍然可以使用标准产品工厂'product'创建平台'Test Platform'的产品,但是调用它创建第二个产品时会失败(如果平台名称设置为唯一)。

    【讨论】:

    【解决方案2】:

    您可以在您的工厂中使用initialize_with 宏并检查对象是否已经存在,然后不要再次创建它。当关联引用该工厂时,这也有效:

    FactoryGirl.define do
      factory :league, :aliases => [:euro_cup] do
        id 1
        name "European Championship"
        owner "UEFA"
        initialize_with { League.find_or_create_by_id(id)}
      end
    end
    

    这里有一个类似的问题,有更多选择:Using factory_girl in Rails with associations that have unique constraints. Getting duplicate errors

    【讨论】:

    • 在 Rails 4 中,您需要使用 League.where(:id => id).first_or_create -- 如果您有一个需要设置信息的 before_save,那么您可能需要 find_or_initialize_by_id 或first_or_initialize
    【解决方案3】:

    @CubaLibre 回答 FactoryBot 版本 5:

    FactoryGirl.define do
      factory :league do
        initialize_with { League.find_or_initialize_by(id: id) }
        sequence(:id)
        name "European Championship"
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多