ex-zac-tly
ex-zac-tly

Reputation: 979

I have overriden the Save method in a model with force=False, how do I use factoryboy to mock the Django model?

For example, see the code below:

class Thing(Model):
    def save(force=False, *args, **kwargs):
        if not force:
             raise Exception("don't save!")

FactoryBoy calls model.get_or_create() which calls model.save(). Is there any way to create an instance of this model in FactoryBoy without modifying the save or get_or_create methods?

Upvotes: 2

Views: 1489

Answers (2)

Xelnor
Xelnor

Reputation: 3589

The default behavior of factory.django.DjangoModelFactory is to call MyModel.objects.create().

If the goal is only for a single call in one test, just use MyModelFactory.build().

If the goal is to never call create(), set the following in your declaration:

class MyModelFactory(factory.django.DjangoModelFactory):
  class Meta:
    model = models.MyModel
    strategy = factory.BUILD_STRATEGY

This maps MyModelFactory() to MyModelFactory.build() instead of the DjangoModelFactory default, MyModelFactory.create().

Upvotes: 3

Yegor Roganov
Yegor Roganov

Reputation: 128

If all you want is a local instance of a Django model, you should use the build strategy. Also, the create strategy invokes _create method, which can be overwritten to meet your needs.

Upvotes: 4

Related Questions