Factory Boy
Factory Boy is an library for Node.js which provides factories for objects creation. It's highly inspired by the fabulous factory_girl library for Ruby on Rails.
It comes with support for :
- associations
- lazy attributes
- defining factory initialization and creation methods
Installation
npm install factory-boy
Defining factories
Factory = require'factory-boy'Factorydefine 'user'class: User->@first_name = 'John'@last_name = 'Smith'= callbacknullMathfloorMathrandom*10000Factorybuild 'user'consolelog userFactorycreate 'user'consolelog user
Custom intialization and creation methods
Factory Boy use initializeWith and createWith methods for building and creating factory objects :
:callbacknullattributes:klasscreateattributescallback
You can overwrite this methods on global level or per each factory :
# overwriting globallyFactory = require'factory-boy'=callbacknullattributes=attributescreatecallback# overwriting per factoryFactorydefine 'user'class: User->=callbacknullklassbuildattributes=attributescreatecallback
Lazy attributes
Attributes defined by functions are evaluated upon object intialization/creation. Lazy functions context are set to factory instance so it's possible to use already defined attributes.
Factorydefine 'user'class: User->@first_name = 'John'=time =callbacknull""
Additionally lazy functions are evaluated in the defined order.
Factorydefine 'user'class: User->= callbacknull10= callbacknull@number1 + 10
Sequences
Sequences can be used for creating record with unique attributes i.e. emails. They are creating lazy attribute for given field with iterator passed as first argument.
Factorydefine 'user'class: User->@sequence 'email'callbacknull"testexample.com"
First variable in callback will be increment for each records, starting from value 1. Therefore creating user factories will return records with unique emails.
Associations
Factorydefine 'user'class: User->@first_name = 'John'@association'profile'Factorydefine 'profile'class: Profile->@avatar_url = 'http://example.com/img.png'Factorycreate 'user'consolelog userprofile_id
When using associations you can pass field name as first parameter.
Factorydefine 'user'class: User->@first_name = 'John'@association'user_profile_id''profile'
Also you can set values to associated factory.
Factorydefine 'user'class: User->@first_name = 'John'@association'profile'avatar_url: 'http://example.com/img2.png'
By default Factory Boy will use id field from associated factory. This can be changed by passing factory options.
Factorydefine 'user'class: User->@first_name = 'John'@association'profile'factory: field: 'external_id'
Contributing
- Fork it
- Install dependencies
npm install
- Make your changes on branch and make sure all tests pass
npm test
- Submit your pull request !