How can i keep my database clean between my scenarios?

65 views Asked by At

I have two scenarios that create a record in a database. Let's say I'm creating a user with [email protected].

Scenario 2 is raising an error that says there is already a record with [email protected]. I think that I need to setup a hook to cleanup database between scenarios.

What is best practice for this stuation? Calling flushdb command between scenarios? Or transaction rollbacks? Or what else?

1

There are 1 answers

0
kevinharvey On

Use the get_or_create method in both scenarios. Don't forget that get_or_create returns a tuple:

>>> from django.contrib.auth.models import User
>>> superman, created = User.objects.get_or_create(username='kal-el')
>>> superman
<User: kal-el>
>>> created
True
>>> superman_returns, created_again = User.objects.get_or_create(username='kal-el')
>>> superman_returns
<User: kal-el>
>>> created_again
False

https://docs.djangoproject.com/en/1.8/ref/models/querysets/#get-or-create