开发者

Creating instances with unique attributes using Factory Girl

开发者 https://www.devze.com 2023-01-07 07:24 出处:网络
I have a constraint and a validation placed on t开发者_开发问答he guid field so that each is unique.The problem is, with the factory definition that I have below, I can create only one user instance,

I have a constraint and a validation placed on t开发者_开发问答he guid field so that each is unique. The problem is, with the factory definition that I have below, I can create only one user instance, as additional instances fail validation.

How do I do this correctly so that the guid field is always unique?

Factory.define(:user) do |u|
  u.guid UUIDTools::UUID.timestamp_create.to_s
end


In general, Factory Girl addresses the problem with sequences:

Factory.define(:user) do |u|
  u.sequence(:guid) { |n| "key_#{n}" }
end

I assume, however, that you do not want to have something iterator-like but a timestamp. This could be done using lazy attributes (that evaluate at runtime):

Factory.define(:user) do |u|
  u.guid { Time.now.to_s }
end

Or, assuming that UUIDTools::UUID.timestamp_create generates a (hopefully suitably formatted) timestamp:

Factory.define(:user) do |u|
  u.guid { UUIDTools::UUID.timestamp_create.to_s }
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号