0

假设我有一个城市模型,其中:

class city
  field :full_name, type: String # San Francisco, CA, United States
  field :_id, type: String, overwrite: true, default: ->{ full_name }
end

假设我在/spec/factories/cities.rb中定义了一个工厂:

FactoryGirl.define do
  factory :city do
    full_name 'San Francisco, CA, United States'
  end
end

在其中一个规范中运行以下代码:

city_attrs = { full_name: 'San Francisco, CA, United States' }
City.create! city_attrs
=> #<City _id: San Francisco, CA, United States, full_name: "San Francisco, CA, United States">

FactoryGirl.create(:city)
=> #<City _id: , full_name: "San Francisco, CA, United States">

如何在不将以下代码添加到/spec/factories/cities.rb的情况下解决此问题?

before(:create) do |city, evaluator|
  city.id = city.full_name
end

编辑解决方案是按照此答案中的建议 停止使用FactoryGirl并改用Fabrication

4

2 回答 2

1

您需要覆盖 FactoryGirl 使用的模型的初始化:

FactoryGirl.define do
  trait :explicit_initialize do
    initialize_with { new(attributes) }
  end

  factory :city, traits: [:explicit_initialize] do
    full_name 'San Francisco, CA, United States'
  end

end
于 2013-10-21T18:00:56.833 回答
0

就像文档中的解释一样,lambda 中的所有默认定义都是惰性的。所以你需要预处理它:

将默认值定义为 proc 时,Mongoid 将在设置所有其他属性后应用默认值。如果您希望这在其他属性之前发生,请设置 pre_processed: true。

class city
  field :full_name, type: String # San Francisco, CA, United States
  field :_id, type: String, overwrite: true, pre_processed: true, default: ->{ full_name }
end
于 2013-10-22T07:16:59.783 回答