Makers
Minimalistic factories to replace fixtures in rails.
Why
I did this gem to:
- Enforce better practices removing unnecessary options.
- Avoid the need to use another method to build/create lists.
- Quicker syntax to handle associations.
Install
Put this line in your Gemfile:
gem 'makers', group: [:development, :test]
Then bundle:
$ bundle
Configuration
Generate de definitions file:
$ bundle exec rails g makers:install
The file will be put in test/makers.rb or spec/makers.rb depending on your test framework:
Makers.define do
end
Usage
Inheritance
Just concatenate makers:
Makers.define do
maker :user do
name 'example'
maker :user_with_email do
email '[email protected]'
end
end
end
Sequences
Generates an unique sequence of numbers for an attribute:
Makers.define do
maker :user do
sequence(:email) { |n| "example#{n}@mail.com" }
sequence(:phone)
end
end
Associations
Associations are defined by name or by the association method:
Makers.define do
maker :user do
posts
comments 4, strategy: :create
end
maker :comment do
association :user
end
maker :post do
user
end
end
Aliases
Aliases can be assigned in the initialization:
Makers.define do
maker :user, aliases: :author do
comments
end
maker :post, aliases: %i(comment article) do
title
end
end
Dependent attributes
If you need to use some logic that depends of another attribute you can use a block:
Makers.define do
maker :user do
name 'example'
email { "#{name}@mail.com" }
sequence(:username) { |n| "#{name}-#{n}" }
end
end
Methods
There are two new methods available in tests:
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:
build :user, 2, name: 'other'
create :category, 5, title: 'other'
Credits
This gem is maintained and funded by mmontossi.
License
It is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.