Create instances with unique attributes using Factory Girl

I have a constraint and validation placed in the guid field so that each one is unique. The problem is that with the factory definition that I have below, I can only create one user instance, since the additional instances do not authenticate.

How to 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
+5
source share
1 answer

In general, Factory Girl solves the sequence problem:

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

I assume, however, that you do not want to have something iterative, but a timestamp. This can be done using lazy attributes (which are evaluated at runtime):

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

, , UUIDTools:: UUID.timestamp_create ( ):

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

All Articles