在测试套件之前加载大量工厂

时间:2014-12-04 10:42:58

标签: ruby-on-rails factory-bot

在我的Rails项目中,我有一个包含很多工厂的工厂文件:

FactoryGirl.define do
  factory :'59000', class: PostalCode do
    value "59000"
    name "toto"
  end
  factory :'59800', class: PostalCode do
    value "59800"
    name "toto"
  end
  factory :'59777', class: PostalCode do
    value "59777"
    name "toto"
  end
  factory :'59910', class: PostalCode do
    value "59910"
    name "toto"
  end
  factory :'59170', class: PostalCode do
    value "59170"
    name "toto"
  end
  factory :'59155', class: PostalCode do
    value "59155"
    name "toto"
  end
  factory :'59510', class: PostalCode do
    value "59510"
    name "toto"
  end
  factory :'59259', class: PostalCode do
    value "59259"
    name "toto"
  end

  ...

end

您是否知道如何在测试套件之前构建/创建此文件包含的所有工厂?

谢谢, 朱

2 个答案:

答案 0 :(得分:1)

解决方案1:

before do
  %w(59000 59259 59510).each do |code|
    create(code)
  end
end

解决方案2:

before do
  FactoryGirl.factories.select { |factory| 
    factory.send(:class_name) == PostalCode 
  }.each{|factory| FactoryGirl.create(factory.name) }
end

解决方案3:

之前的一些变体。

答案 1 :(得分:0)

解决方案2太棒了!非常感谢!

我只是喜欢它:

  config.before(:suite) do
    FactoryGirl.factories.select { |factory|
      factory.send(:class_name) == PostalCode
    }.each{|factory| FactoryGirl.create(factory.name) }
  end

在我的rails_helper配置文件中,我的所有邮政编码都是我数据库中的种子。

再次,谢谢!