我有一个这样定义的模型

class Lga < ActiveRecord::Base
  validates_uniqueness_of :code
  validates_presence_of :name
end


我已经为Lgas定义了一家工厂

Factory.sequence(:lga_id) { |n| n + 10000 }

Factory.define :lga do |l|
  id = Factory.next :lga_id
  l.code "lga_#{id}"
  l.name "LGA #{id}"
end


但是,当我跑步时

Factory.create(:lga)
Factory.create(:lga)


script/console中,我得到

>> Factory.create(:lga)
=> #<Lga id: 2, code: "lga_10001", name: "LGA 10001", created_at: "2010-03-18  23:55:29", updated_at: "2010-03-18 23:55:29">
>> Factory.create(:lga)
ActiveRecord::RecordInvalid: Validation failed: Code has already been taken

最佳答案

问题在于codename属性不是所谓的惰性属性。我曾想写类似的东西:

Factory.define :lga do |l|
  l.code { |n| "lga_#{n+10000}" }
end


但我也想重用name属性中的ID。你可以确定
每次调用id并将其放在Factory.create挂钩中时,对after_build进行评估。

Factory.define :lga do |l|
   l.after_build do |lga|
     id = Factory.next :lga_id
     lga.code = "lga_#{id}"
     lga.name = "LGA #{id}"
   end
end


仅在FactoryGirl 1.2.3及更高版本中有效。

10-06 03:35