Search code examples
pythondjangounit-testingfactoryfactory-boy

How to let DjangoModelFactory create a model without saving it to the DB?


I'm writing unit tests in a Django project. I've got a factory to create objects using the .create() method. So in my unit tests I'm using this:

device = DeviceFactory.create()

This always creates a record in the DB though. Is there a way that I can make the factory create an object without saving it to the DB yet?

I looked over the documentation but I can't find it. Am I missing something?


Solution

  • Quoth this bit of the documentation, use .build() instead of .create():

    # Returns a User instance that's not saved
    user = UserFactory.build()
    
    # Returns a saved User instance.
    # UserFactory must subclass an ORM base class, such as DjangoModelFactory.
    user = UserFactory.create()
    
    # Returns a stub object (just a bunch of attributes)
    obj = UserFactory.stub()
    
    # You can use the Factory class as a shortcut for the default build strategy:
    # Same as UserFactory.create()
    user = UserFactory()