Machinist 2

Introduction

Note: Machinist isn't under active development. See the Status section below for more info.

Machinist makes it easy to create objects for use in tests. It generates data
for the attributes you don't care about, and constructs any necessary
associated objects, leaving you to specify only the fields you care about in
your test. For example:

describe Comment, "without_spam scope" do
it "doesn't include spam" do
# This will make a Comment, a Post, and a User (the author of the
# Post), generate values for all their attributes, and save them:
spam = Comment.make!(:spam => true)
Comment.without_spam.should_not include(spam)
end
end

Rails 2

Usage

Blueprints

A blueprint describes how to generate an object. The blueprint takes care of
providing attributes that your test doesn't care about, leaving you to focus on
just the attributes that are important for the test.

A simple blueprint might look like this:

Post.blueprint do
title { "A Post" }
body { "Lorem ipsum..." }
end

You can then construct a Post from this blueprint with:

Post.make!

When you call make!, Machinist calls Post.new, then runs through the
attributes in your blueprint, calling the block for each attribute to generate
a value. It then saves and reloads the Post. (It throws an exception if the
Post can't be saved.)

You can override values defined in the blueprint by passing a hash to make:

Post.make!(:title => "A Specific Title")

If you want to generate an object without saving it to the database, replace
make! with make.

Unique Attributes

For attributes that need to be unique, you can call the sn method from
within the attribute block to get a unique serial number for the object.

User.blueprint do
username { "user-#{sn}" }
end

Associations

If your object needs associated objects, you can generate them like this:

Comment.blueprint do
post { Post.make }
end

Calling Comment.make! will construct a Comment and its associated Post, and
save both.

Machinist is smart enough to look at the association and work out what sort of
object it needs to create, so you can shorten the above blueprint to:

Comment.blueprint do
post
end

If you want to override the value for post when constructing the comment, you
can do this: