DjangoCon 2022 | factory_boy: testing like a pro

Django developers, boost your testing skills with best practices for using factories, avoiding repetition and explicit language, and simplifying your code.

Key takeaways
  • Best practices for testing: use factories, avoid repetition, and use explicit language.
  • Customs and definitions: analyze larger systems, start with the high-level view, and then drill down to details.
  • Simplest way possible approach: do not create objects manually, do not use fixtures, use factories.
  • Single-specific problem: best practices don’t care about why, it’s just best practices.
  • If something creates a hard-to-reproduce bug, that’s not Factory Boy‘s fault.
  • Setup the test having the most output already there, like a highly adopted technique.
  • Best practice: view, Issue, Use models in the factory as you view them in the test.
  • Relation: another guide you can consult, for better understanding.
  • other source/result / resource: and you always make the most you need.
  • Short summary: So the main idea here is to look at your testing and your code in general and try to see where you can standardize, try to simplify the code, and also try to reduce the number of tests you have. We have the poll and the question factories. The poll is a pretty complex object, so it’s really good that we can have in our factories and then use them to build the poll, so we can make sure that it’s working as expected. Another thing that’s really important is the relationships between objects. So for example, if you have a poll that has choices, then you can use the related factory to create the choices. Remember, always build a valid object, just like you would do in real life.