[Django]-Why is factory_boy superior to using the ORM directly in tests?

27đź‘Ť

âś…

Yes, you can prepare your test data by using django ORM directly. But there are advantages of using factories and factory_boy specifically, here are some of that I remember and use:

  • your model factories are defined in a nice, clean and readable manner:

    class CasesFactory(factory.Factory):
        FACTORY_FOR = models.Case
    
        number = factory.Sequence(lambda n: '1021-{0}'.format(n))
        create_date = datetime.datetime.now()
    
  • another benefit of this class-based approach is the ability to create SubFactories

  • also you can easily define factories for different kind of relationships: ForeignKey, reverse ForeignKey, ManyToMany (documentation)

  • neat DjangoModelFactory class
  • Sequences (as you’ve mentioned) helps make the data more “dynamic”. Imagine handling it yourself.
  • mute_signals decorator – sometimes while testing you don’t want the signal to be dispatched

Basically, factory_boy is there to avoid writing “helper” functions for generating test data. Instead, it introduces a nice and easy-to-use interface to it.

Ask yourself: why reinvent the wheel is there is a tool specifically for the job?

Also see:

👤alecxe

Leave a comment