Rails: Avoiding duplication errors in Factory Girl…am I doing it wrong?

前端 未结 4 967
花落未央
花落未央 2021-01-31 16:00

Suppose I have a model user, which has a uniqueness constraint on the email field

If I call Factory(:user) once all is well, but i

4条回答
  •  臣服心动
    2021-01-31 16:09

    I found this a nice way to be sure the tests will always pass. Otherwise you can not be sure the 100% of the times you will create a unique email.

    FactoryGirl.define do
      factory :user do
        name { Faker::Company.name }
        email { generate(:email) }
      end
      sequence(:email) do
        gen = "user_#{rand(1000)}@factory.com"
        while User.where(email: gen).exists?
          gen = "user_#{rand(1000)}@factory.com"
        end
        gen
      end
    end
    

提交回复
热议问题