Closed igorsimb closed 6 months ago
test.py
from journal.entries.tests.factories import EntryFactory
class TestEntry:
def test_factory(self):
"""A factory produced a valid journal etry."""
entry = EntryFactory()
assert entry.body != ""
assert entry.when is no None
assert entry.user is not None
factories.py
import factory
import datetime
class EntryFactory(factory.django.DjangoModelFactory):
class Meta:
model = "entries.Entry"
body = factory.Faker('paragraph')
when = factory.LazyFunction(datetime.date.today)
# basically a foreign key to the user factory that we created
user = factory.SubFactory("journal.accounts.tests.factories.UserFactory")
models.py
class Entry(models.Model):
"""An entry stores the user's writing for the day"""
body = models.Textfield()
when = models.DateField()
user = models.Foreignkey("accounts.CustomUser", on_delete=models.CASCADE, related_name="entries")
Closing as solved in https://github.com/igorsimb/mp-monitor/pull/72
Create a conftest file to contain a fixture that is autoused to access django db.
conftest.py
Use Factory Boy (from Matt Layman stream)
Replaces the million fixtures. Factory boy is able to auto create any foreign_key dependancies that you may need in a test (after you create a factory for them) without having to specify them every time.
pip install factory_boy
factories.py
Write tests using the created factory
test_user.py