I have a Factory Girl factory that needs to generate a unique name using Faker. Unfortunately, Factory Girl generates duplicates relatively frequently, which causes intermittent test errors. I previously added a random integer after the Faker name, but I am now checking the database to make sure that a potential name from Faker doesn't already exist.
FactoryGirl.define do factory :company do name do name = Faker::Company.name name = Faker::Company.name while Company.exists?(name: name) name end end end
The above code works but seems inelegant. I'm assigning name in the first row of the block so that only one DB lookup (instead of two) will be necessary in the most common case where a Fake name is unique.
I end the block with
name as otherwise the
while statement returns nil when the loop ends.