<img src=“https://badge.fury.io/rb/fabricators.png” alt=“Gem Version” /> <img src=“https://codeclimate.com/github/museways/fabricators.png” /> <img src=“https://travis-ci.org/museways/fabricators.png?branch=master” alt=“Build Status” /> <img src=“https://gemnasium.com/museways/fabricators.png” alt=“Dependency Status” />
Fabricators
Minimalistic factory alternative inspired in factory_girl.
Install
Put this line in your Gemfile:
gem 'fabricators'
Then bundle:
$ bundle
Configuration
There is no need to configure the rails application, the gem will do it automatically.
Usage
Methods
There are three methods available:
Fabricators.attributes_for
Fabricators.build
Fabricators.create
To not write “Fabricators” every time you can include the methods in your tests:
class ActiveSupport::TestCase
include Fabricators::Methods
end
Then you can you just:
attributes_for
build
create
Is possible to override the defaults passing a hash:
build :user, name: 'other'
create :category, title: 'other'
To create lists just pass the desired size as second parameter to build and create:
build :user, 2, name: 'other'
create :category, 5, title: 'other'
Fabricators
The way you define your fabricators should be very familiar already.
Fabricators.define do
fabricator :user do
name 'example'
end
end
Inehritance
Can be declare nested or separate:
Fabricators.define do
fabricator :user do
name 'example'
fabricator :user_with_email do
email '[email protected]'
end
end
fabricator :user_with_age, parent: :user do
age 9
end
end
Generators
Define them outside your fabricators and use them as attributes:
Fabricators.define do
generator(:name) { 'example' }
generator(:email) { |n| "example#{n}@mail.com" }
generator(:age)
fabricator :user do
name
email
age
end
end
Associations
Associations are declared just by the name of the association:
Fabricators.define do
fabricator :user do
posts
comments 4 # By default 1, but can be overwritten
end
fabricator :post do
user
end
fabricator :comment do
user
end
end
Aliases
The aliases are essential when there is the need of context:
Fabricators.define do
generator(:title, aliases: [:first_name, :last_name]) { 'example' }
fabricators :user, aliases: :author do
first_name
last_name
comments
end
fabricators :post, aliases: :comment do
title
end
end
Dependent attributes
If you need to use some logic that depends of another attribute you can go:
Fabricators.define do
fabricators :user do
name 'example'
email { "#{name}@mail.com" }
end
end
Callbacks
The available callbacks are before(:build), before(:create), after(:build) and after(:create):
Fabricators.define do
before(:build) { |u| u.name = 'global' }
fabricator :user do
after(:build) { |u| u.name = 'local' }
end
end