FactoryBot 和 Faker - unique 不起作用

FactoryBot and Faker - unique is not working

我正在使用 FactoryBot 和 Faker 进行测试,看起来 Faker 正在生成相同的名称:

class Profile < ApplicationRecord
  belongs_to :user
  validates_presence_of :first_name, :last_name, :nickname
  validates :nickname, uniqueness: { case_sensitive: false }
end

FactoryBot.define do
  factory :user do
    sequence(:email) { |n| "user#{n}@example.org" }
    password "123456"
    trait :with_profile do
      profile
    end
  end
end

FactoryBot.define do
  factory :profile do
    first_name Faker::Name.unique.first_name
    last_name Faker::Name.unique.last_name
    nickname { "#{first_name}_#{last_name}".downcase }
    user
  end
end

RSpec.feature "Friendships", type: :feature do
  scenario "User can accept a pending friendship request" do
    @tom   = create(:user, :with_profile)
    @jerry = create(:user, :with_profile)
    #other stuff
  end
end

即使我使用独特的方法,我也会收到错误

ActiveRecord::RecordInvalid: Validation failed: Nickname has already been taken`.

有什么线索吗?

应该是:

first_name { Faker::Name.unique.first_name }
last_name { Faker::Name.unique.last_name }

加载时 Faker::Name.unique.first_name 将被评估。因此,使用块。

编辑:

FactoryBot.define do
  factory :profile do
    first_name Faker::Name.unique.first_name
  end
end

在此示例中,Faker::Name.unique.first_name 将在工厂定义期间被评估一次(当文件为 loaded/required 时)。如果它找到一个唯一值,比如 'John Doe' 它将用于该工厂创建的每个项目。

或者换句话说:加载文件并Faker::Name.unique.first_name评估后,您可能会认为这个工厂是:

FactoryBot.define do
  factory :profile do
    first_name 'John Doe'
  end
end

当您使用块时 - 每次调用 create(:profile)build(:profile) 时都会评估块的主体。块内的 Faker::Name.unique.first_name 部分每次都会被调用,并且 return 不同的、唯一的结果。