我在Factory Girl中使用一个序列来获取唯一值,但我收到了验证错误

时间:2010-03-18 23:58:09

标签: ruby-on-rails factory-bot

我有这样定义的模型

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

2 个答案:

答案 0 :(得分:7)

问题是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及以上版本。

答案 1 :(得分:2)

之前的答案仍然正确,但在较新版本的FactoryGirl中,您会收到警告。

Factory.next has been depreciated. Use FactoryGirl.generate instead.

新代码应如下所示:

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

来源:http://notesofgreg.blogspot.co.uk/2012/07/foolproof-factorygirl-sequence.html