如何将单个记录与多个工厂女孩模型相关联?

How do I associate a single record with a multiple factory girl models?

我有一个用户模型和一个国家模型。国家的数量有限(目前只有 1 个),在我的工厂中,我不确定如何将每个用户记录与一个国家相关联。我尝试创建一个国家工厂并将每个用户与一个国家相关联,但由于我的国家数据是静态的,它试图为每个用户创建一个新国家,但失败了,因为我对国家进行了唯一性验证。这是我尝试过的:

  factory :country do
    country_iso 'GB'
    country_code 44
    country 'United Kingdom'
    active true
  end

  factory :user do
    email { Faker::Internet.email }
    password { Faker::Internet.password(10) }
    country

    after(:create) do |usr, evaluator|
      create_list(:canned_response, 3, user: usr)
    end

    trait :admin do
      admin true
    end
  end

如何创建一个国家/地区,每个创建的用户工厂都将与之相关联?

您可以使用现有的国家或创建一个如果 none 存在:

factory :user do
  email { Faker::Internet.email }
  password { Faker::Internet.password(10) }
  country { Country.first || create(:country) }

  # ...
end