Gem Version Code Climate Build Status Dependency Status

Fabricators

Minimalistic factory inspired in factory_girl for rails.

Install

Put this line in your Gemfile:

gem 'fabricators', group: [:development, :test]

Then bundle:

$ bundle

Configuration

There is no need to configure anything, all this is done automatically for rspec and minitest:

  • Loading the definitions.
  • Replacing the fixtures generators.
  • Including the methods inside your testing framework.
  • Cleaning the database after each test.

Usage

Methods

There are three methods available:

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 methods:

build :user, 2, name: 'other'
create :category, 5, title: 'other'

Fabricators

Define them in a ruby file inside test/fabricators or spec/fabricators folders:

fabricator :user do
  name 'example'
end

Inheritance

Can be declare nested or separated:

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

Sequences

Generates an unique sequence of numbers for the attribute of the fabricator:

fabricator :user do
  sequence(:email) { |n| "example#{n}@mail.com" }
  sequence(:age)
end

Associations

Associations are used by name:

fabricator :user do
  posts
  comments 4 # You can customize the number of records
end
fabricator :post do
  user
end
fabricator :comment do
  user
end

Aliases

The aliases are important when there is the need of context:

fabricators :user, aliases: :author do
  comments
end
fabricators :post, aliases: :comment do
  title
  author
end

Dependent attributes

If you need to use some logic that depends of another attribute you can use a block or sequence:

fabricators :user do
  name 'example'
  email { "#{name}@mail.com" }
  sequence(:username) { |n| "#{name}-#{n}" }
end

Callbacks

The available callbacks are before(:build), before(:create), after(:build) and after(:create):

fabricator :user do
  after(:build) { |u| u.name = 'sample' }
end

You can declare global callbacks in your test or spec helper as well:

Fabricators.configure do
  after(:create) do |object|
    log object.errors unless object.valid?
  end
end

Credits

This gem is maintained and funded by museways.

License

It is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.