How to use Faker from Factory_boy How to use Faker from Factory_boy python python

How to use Faker from Factory_boy


You can use faker with factory_boy like this:

class RandomUserFactory(factory.Factory):    class Meta:        model = models.User    first_name = factory.Faker('first_name')user = RandomUserFactory()print user.first_name# 'Emily'

So you need to instantiate a user with factory_boy and it will call Faker for you.

I don't know if you are trying to use this with Django or not,but if you want the factory to save the created user to the database,then you need to extend factory.django.DjangoModelFactory instead of factory.Factory.


I know this is an old question but for anyone who might come across this, here's another approach that you can use.

>>> from factory.faker import faker>>> FAKE = faker.Faker()>>> FAKE.name()'Scott Rodriguez'>>> FAKE.address()'PSC 5061, Box 1673\nAPO AP 53007'>>>


UPD You should generally prefer one of the two other answers, because this ones uses the private interface, and the generate() solution only works for factory-boy<3.1.0.

A bit simpler way is to use undocumented generate() method (factory-boy<3.1.0):

import factoryprint(factory.Faker('random_int').generate({}))

or _get_faker():

print(factory.Faker._get_faker().random_int())

You may check out the other answer for a more detailed example.