I'm writing unit tests for my Django app. Currently I'm using factory_boy to make fake objects for testing. This works fine for most of my tests, but I'm having the following problem: My factory_boy objects aren't showing up in {model}.objects. For example, I'm trying to test the following method in my serializer:
def get_can_edit(self, obj):
request = self.context.get('request')
user = request.user
admin = SimpleLazyObject(obj.admin)
user = User.objects.get(username=request.user)
return user == obj.admin
Going through it with a debugger, I've determined that request.user correctly has my fake user, but User.objects does not have my fake user.
I'm wondering if there's a simple alternative to factory_boy that will actually add my fake objects to {model}.objects or if I'm just using factory_boy incorrectly? Or maybe there's a whole different approach... who knows.
Here's the code:
The serializer
The test
You need to inherit from DjangoModelFactory instead of Factory base class in your UserFactory for objects to be saved onto the database.
From factory_boy docs:
All factories for a Django
Modelshould use theDjangoModelFactorybase class.
class UserFactory(factory.DjangoModelFactory): # use DjangoModelFactory base class
class Meta:
model = models.User
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With