How to use Faker from Factory_boy

marcanuy picture marcanuy · Jul 31, 2016 · Viewed 9.2k times · Source

Factory_boy uses fake-factory (Faker) to generate random values, I would like to generate some random values in my Django tests using Faker directly.

Factory_boy docs suggests using factory.Faker and its provider as :

class RandomUserFactory(factory.Factory):
    class Meta:
        model = models.User

    first_name = factory.Faker('first_name')

But this isn't generating any name:

>>> import factory
>>> factory.Faker('name')
<factory.faker.Faker object at 0x7f1807bf5278>
>>> type(factory.Faker('name'))
<class 'factory.faker.Faker'>

From factory_boy faker.py class factory.Faker('ean', length=10) calls faker.Faker.ean(length=10) but Faker docs says it should show a name:

from faker import Faker
fake = Faker()
fake.name()
# 'Lucy Cechtelar'

Is there any other way to use Faker instead of setting an instance directly from Faker?

from faker import Factory
fake = Factory.create()
fake.name()

Answer

rlaszlo picture rlaszlo · Aug 2, 2016

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.