This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Machinist Cheatsheet

A quick reference guide for Machinist: Ruby fixture replacement library blueprints, object instantiation, and model associations.

· Published

[!NOTE] Archived Project: Machinist has been discontinued since 2013. For modern Ruby on Rails testing fixtures, consider using FactoryBot.

Machinist is a fixture-replacement library for Ruby that allows defining model blueprints to generate valid test instances on the fly.

Installation

Add to your Gemfile:

group :test do
  gem 'machinist', '>= 2.0.0.beta2'
end

Run bundle and the install generator:

bundle install
rails generate machinist:install

Defining Blueprints

Define default model properties using serial numbers (sn) to guarantee uniqueness:

User.blueprint do
  name  { "User #{sn}" }
  email { "user-#{sn}@example.com" }
end

# Named variant blueprint
User.blueprint(:admin) do
  name  { "Admin #{sn}" }
  admin { true }
end

Building Objects in Tests

# Build in-memory without saving
user = User.make

# Build and persist to database
user = User.make!

# Override blueprint attributes
user = User.make!(name: "David")

# Use a named blueprint
admin = User.make!(:admin)

Associations

Post.blueprint do
  title  { "Post #{sn}" }
  author { User.make }       # Belongs-to association
  comments(3)                # Has-many association (generates 3 items)
  author                     # Auto-detects and calls User.blueprint
end

References

Related topics