Testing in Django (Part 2) - Model Mommy vs. Django Testing Fixtures

In the last post, I introduced you to testing in Django and we looked at best practices as well as a few examples. This time, I’ll show you a bit more complicated example and introduce you to Model Mommy for creating sample data.

Why should you care?

In the last post, I said that, “factory_boy, model_mommy, and mock are all are used in place of fixtures or the ORM for populating needed data for testing. Both fixtures and the ORM can be slow and need to be updated whenever your model changes.”

To summarize, the Django Testing Fixtures are problematic because they-

must be updated each time your model/schema changes,

are really, really slow, and

sometimes hard-coded data can cause your tests to fail in the future.

So, by using Model Mommy you can create fixtures that load quicker and are much easier to maintain over time.

Django Testing Fixtures

Let’s start by looking at our example for testing the model in the last post:

123456789

classWhateverTest(TestCase):defcreate_whatever(self,title="only a test",body="yes, this is only a test"):returnWhatever.objects.create(title=title,body=body,created_at=timezone.now())deftest_whatever_creation(self):w=self.create_whatever()self.assertTrue(isinstance(w,Whatever))self.assertEqual(w.__unicode__(),w.title)

Here we simply created a Whatever() object and asserted that the created title matched the expected title.

If you downloaded the Project from the repo, fire up the server and run the tests:

1

$ coverage run manage.py test whatever -v 2

You will see that the above tests pass:

1

test_whatever_creation (whatever.tests.WhateverTest) ... ok

Now, instead of having to create a new instance, with each attribute, each time (boring!), we can use Model Mommy to streamline the process.