【问题标题】:FactoryBot and Faker - unique is not workingFactoryBot 和 Faker - unique 不起作用
【发布时间】:2018-10-29 20:58:33
【问题描述】:

我正在使用 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`.

有什么线索吗?

【问题讨论】:

    标签: ruby-on-rails ruby rspec factory-bot faker


    【解决方案1】:

    应该是:

    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 将在工厂定义期间(加载/需要文件时)评估一次。如果它找到一个唯一值,比如“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 部分,并返回不同的、唯一的结果。

    【讨论】:

    • 非常感谢!你能更好地解释一下为什么没有这个块它就不能工作吗?
    • FactoryBot 将属性分为静态和动态。动态属性最好的解释是here
    • 在第一个示例中,Faker::Name.unique.first_name 被评估一次(在文件加载期间),使用该工厂创建的每个项目都将获得它评估的(相同)值。在解决方案中,它是一个块,每次使用此工厂创建项目时都会评估它的主体。
    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 2011-03-30
    • 1970-01-01
    • 2017-02-09
    • 2019-02-18
    • 1970-01-01
    相关资源
    最近更新 更多