Factory Boy can help you during testing Django Apps

During my work with the team, i learned a lot from them. Especially with CTO and my friends there. They taught me by giving a test code that is so beautiful. With Django Factory Boy I can create a shadow object during the testing phase without needing to create objects from the queryset that make it so simple.

This note gives me feedback in the future. I keep using this note for my reference in the code testing phase in Django Framework.

For installation, it’s pretty easy. I only need a package named factory_boy which includes the Faker packages.

If you want to see full reference from factory_boy, you can visit this link.

How to use ?

How to use it is quite easy. In this case I have a simple model class, called Product model.

Then, iwill create a tests directory. However, I need to delete the tests.py file inside my app before making it.

Then I will create a structure like this inside my app:

The factories.py file contains the factory product that will create the product object as long as I call it in the testing phase. It will create as many objects as I want in testing. While the test_products_v1.py file contains the test code for the product.

The contents of the factories.py file are as follows:

Look at the fields. It’s like a field on a model that’s in the Product model. In the Meta class, there is one attribute named model. This attribute contains a value referencing my Product model that has the format <appname>. <ModelName>.

Ok, if we make the test in the file test_products_v1.py, more or less we will use the Factory class we have created earlier:

Simple and so elegant. I love it. Django & Python is fucking awesome.

Stay code stay life.