0

I created UserFactory class in factories.py as shown below. I use pytest-django and pytest-factoryboy in Django:

# "factories.py"

import factory

from django.contrib.auth.models import User

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

    username = "John"

Then, I registered UserFactory class in conftest.py as shown below:

# "conftest.py"

import pytest

from pytest_factoryboy import register
from tests.factories import UserFactory

register(UserFactory)

Then, I created test_user() which prints username with user_factory and user_factory.build() and user_factory.create() in test_ex1.py as shown below:

# "test_ex1.py"

import pytest

from django.contrib.auth.models import User

def test_user(db, user_factory):
    print(user_factory.username) # Here
    print(user_factory.build().username) # Here
    print(user_factory.create().username) # Here
    assert True

Then, I got 3 John's as shown below:

$ pytest -q -rP
.                                [100%]
=============== PASSES ================
____________ test_new_user ____________
-------- Captured stdout call ---------
John
John
John
1 passed in 0.55s

My questions:

  1. What is the difference between user_factory, user_factory.build() and user_factory.create() in Factory Boy?
  2. When should I use user_factory, user_factory.build() and user_factory.create() in Factory Boy?
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129

1 Answers1

0
  • build provides a local object

  • create instantiates a local object, and saves it to the database.

https://factoryboy.readthedocs.io/en/stable/introduction.html#strategies

Your 'second John' has not been saved to the database while the third one has.

CoffeeBasedLifeform
  • 2,296
  • 12
  • 27