Faker is producing duplicate data when used in factory_girl

后端 未结 4 1752
天涯浪人
天涯浪人 2020-12-08 01:48

I\'m trying to populate some fake data into a factory using the Faker gem:

Factory.define :user do |user|
  user.first_name Faker::Name::first_name
  user.la         


        
4条回答
  •  忘掉有多难
    2020-12-08 02:01

    A (less efficient) alternative to using sequences when you have a uniqueness validation on an attribute is to check whether a proposed value already exists and keep trying new ones until it's unique:

    FactoryGirl.define do
      factory :company do
        name do
          loop do
            possible_name = Faker::Company.name
            break possible_name unless Company.exists?(name: possible_name)
          end
        end
      end
    end
    

提交回复
热议问题