0
votes

I have a User model and Country model. There are a limited set of countries (only 1 right now) and in my factory, I'm not sure how to associate each User record with a single Country. I tried creating a country factory and associating each user with a country but since my country data is static, it tried to create a new country for each user, which failed because i have uniqueness validations on country. Here's what I tried:

  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

How do I create a single Country that each user factory created will be associated with?

1

1 Answers

0
votes

You can use the existing country or create one if none exists:

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

  # ...
end