1

I would like to create a Person instance with Model Bakery. My Person model looks like this:

User = get_user_model()

class Person(models.Model):
    user = models.OneToOneField(User, related_name="friend", on_delete=CASCADE)
    country = models.CharField(max_length=100)

My baker_recipes.py looks like this:

from model_bakery.recipe import Recipe

User = get_user_model()
test_user = User(username="test_user")

person = Recipe(Person, user = test_user)

My tests.py looks like this:

import pytest
from model_bakery import baker

@pytest.mark.django_db()
class TestPerson:
    def setup(self):
        self.person = baker.make_recipe("company.tests.person")

    def test_country_access(self):
        assert True

But when I run pytest with this set up I get the following error:

django.db.utils.IntegrityError: insert or update on table "company_person" violates foreign key constraint "company_person_user_id_4f1cc5d0_fk_auth_user_id"
DETAIL:  Key (user_id)=(411) is not present in table "auth_user".
Andrew Einhorn
  • 741
  • 8
  • 23
  • What is `Recipe(Person, user = test_user)` (especially `Person` and the `Recipe`) doing here? – Willem Van Onsem Jul 30 '21 at 09:17
  • I've edited my question to provide more context. Recipe is a class from Model Bakery that allows you to specify the inputs to a particular instance you want to create. When you call baker.make_recipe, it then makes the recipe (i.e. creates and populates a temporary database table with this data) – Andrew Einhorn Jul 30 '21 at 12:52
  • Can you show `Recipe` – Brian Destura Jul 31 '21 at 07:16

1 Answers1

1
    import pytest
    from model_bakery import baker
    
    @pytest.mark.django_db()
    class TestPerson:
        def setup(self):
            # replace this
            self.person = baker.make_recipe("company.tests.person")
            # with this
            self.person = baker.make(Person, ...optional_field_params)
    
        def test_country_access(self):
            assert a_condition_is_true
            # assert True is not logical here so comented out

N.B with baker.make the created instance is persisted to the test db on setup with baker.prepare on the other hand it is not persisted.

David Wolf
  • 1,400
  • 1
  • 9
  • 18
iamcoder
  • 21
  • 5