假设我有一个城市模型:
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
代替this answer
答案 0 :(得分: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
答案 1 :(得分:0)
就像文档解释一样,lambda中的所有默认定义都是懒惰的。所以你需要pre_process它:
将默认值定义为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