I'm using factory_boy to create test fixtures. I've got two simple factories, backed by SQLAlchemy models (simplified below).
I'd like to be able to call AddressFactory.create()
multiple times, and have it create a Country
if it doesn't already exist, otherwise I want it to re-use the existing record.
class CountryFactory(factory.Factory):
FACTORY_FOR = Country
cc = "US"
name = "United States"
class AddressFactory(factory.Factory):
FACTORY_FOR = Address
name = "Joe User"
city = "Seven Mile Beach"
country = factory.SubFactory(CountryFactory, cc="KY", name="Cayman Islands")
My question is: how can I set up these factories so that factory_boy doesn't try to create a new Country every time it creates an Address?
In the latest factory-boy==2.3.1 you can add FACTORY_DJANGO_GET_OR_CREATE
class CountryFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = 'appname.Country'
FACTORY_DJANGO_GET_OR_CREATE = ('cc',)
cc = "US"
name = "United States"
Assuming cc field is the unique identifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With