Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding duplicates with factory_boy factories

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?

like image 620
Jim Stewart Avatar asked Oct 02 '13 21:10

Jim Stewart


Video Answer


1 Answers

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.

like image 93
Nam Ngo Avatar answered Nov 15 '22 14:11

Nam Ngo