Creating instances with unique attributes using Factory Girl
Asked Answered
L

1

7

I have a constraint and a validation placed on the 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
Lennielenno answered 14/7, 2010 at 13:19 Comment(0)
S
11

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
Sheave answered 14/7, 2010 at 13:48 Comment(1)
+1 The reason the OP is having the problem is because the guid creation code is evaluated at Factory definition time so the value is constant for each invocation of the factory. The third of your three possible solutions will generate a new GUID on each invocation of the factory, which is almost certainly what the OP is looking for.Flagpole

© 2022 - 2024 — McMap. All rights reserved.