factory_boy is a fixtures replacement based on thoughtbot's factory_girl . Like factory_girl it has a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute dicts, and stubbed objects), and support for multiple factories for the same class, including factory inheritance. Django support is included, and support for other ORMs can be easily added.
The official repository is at http://github.com/rbarrois/factory_boy.
This README parallels the factory_girl README as much as possible; text and examples are reproduced for comparison purposes. Ruby users of factory_girl should feel right at home with factory_boy in Python.
factory_boy was originally written by Mark Sandstrom, and improved by Raphaël Barrois.
Thank you Joe Ferris and thoughtbot for creating factory_girl.
# Download the source and run python setup.py install
Factories declare a set of attributes used to instantiate an object. The name of the factory is used to guess the class of the object by default, but it's possible to explicitly specify it:
import factory from models import User # This will guess the User class class UserFactory(factory.Factory): first_name = 'John' last_name = 'Doe' admin = False # This will use the User class (Admin would have been guessed) class AdminFactory(factory.Factory): FACTORY_FOR = User first_name = 'Admin' last_name = 'User' admin = True
factory_boy supports several different build strategies: build, create, attributes and stub:
# Returns a User instance that's not saved user = UserFactory.build() # Returns a saved User instance user = UserFactory.create() # Returns a dict of attributes that can be used to build a User instance attributes = UserFactory.attributes() # Returns an object with all defined attributes stubbed out: stub = UserFactory.stub()
You can use the Factory class as a shortcut for the default build strategy:
# Same as UserFactory.create() user = UserFactory()
The default strategy can be overridden:
UserFactory.default_strategy = factory.BUILD_STRATEGY user = UserFactory()
The default strategy can also be overridden for all factories:
# This will set the default strategy for all factories that don't define a default build strategy factory.Factory.default_strategy = factory.BUILD_STRATEGY
No matter which strategy is used, it's possible to override the defined attributes by passing keyword arguments:
# Build a User instance and override first_name user = UserFactory.build(first_name='Joe') user.first_name # => 'Joe'
2 weeks ago passed
.. image:: https://readthedocs.org/projects/factoryboy/badge/?version=latest :target: http://factoryboy.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status
<a href='http://factoryboy.readthedocs.io/en/latest/?badge=latest'> <img src='https://readthedocs.org/projects/factoryboy/badge/?version=latest' alt='Documentation Status' /> </a>
Project Privacy Level