使用FactoryGirl定义多个自定义记录

时间:2017-05-09 12:26:51

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

我想使用FactoryGirl创建一个键和值的哈希值。我经历了一个具有类似要求的POST,但无法理解实现我想要的方法。以下是我的尝试:

statuses = {
  "holding_status" => "Holding",
  "scheduled_status" => "Scheduled",
  "submitted_status" => "Submitted",
  "cancelled_status" => "Cancelled",
  "failed_status" => "Failed",
  "none_status" => nil
}

statuses.each do |code, name|
  FactoryGirl.define do
    factory :submit_statuses do
      code code
      name name
    end
  end
end

但是,它给了我以下错误(预期):

  

/var/lib/gems/2.2.0/gems/factory_girl-4.5.0/lib/factory_girl/decorator.rb:10:in   `method_missing':工厂已注册:   submit_statuses(FactoryGirl :: DuplicateDefinitionError)

编辑(另一种尝试)

FactoryGirl.define do
  statuses.each do |code, name|
    factory "submit_#{code}" do
      code code
      name name
    end
  end
end

create(:submit_holding_status)
create(:submit_scheduled_status)
create(:submit_submitted_status)
create(:submit_cancelled_status)
create(:submit_failed_status)
create(:submit_none_status)

1 个答案:

答案 0 :(得分:1)

您希望如何打电话给这家工厂?我有点不清楚你希望在这里取得什么。

我建议的一种可行方法是将每种状态类型定义为factory trait

prod