Machinist is a Rails plugin to help populate your database with data for tests.
You specify a "blueprint" for each of your models, with reasonable defaults for the various fields. In your test setup, you use the blueprint to generate data, overriding any fields you need set for that particular test.
This keeps each of your tests together with the data it depends on, but avoids cluttering the test with details of all the model fields that aren't relevant for that test.
If you're familiar with ThoughtBot's factory_girl, this is similar, but has a much cleaner syntax.
Create a blueprints.rb file in your test (or spec) directory, and require it in your test_helper.rb (or spec_helper.rb).
Post.blueprint do
title "Example Post"
body "Lorem ipsum dolor sit amet"
end
Comment.blueprint do
post
author { Sham.name } # Use the Sham to generate a name. See docs below.
body "Lorem ipsum dolor sit amet"
end
In your tests, you can now do things like:
# Create a Post in the database.
@post = Post.make
# Create a Post with a different title.
@post = Post.make(:title => "A Different Title")
# Create a Comment and a corresponding Post.
@comment = Comment.make
# Create a Post with several Comments.
@post = Post.make
3.times { Comment.make(:post => @post) }
Sham lets you generate random but repeatable unique values for blueprints.
For example, you could put this in your blueprints.rb:
# Tell sham how to generate a random name (using the Faker gem in this case).
Sham.name { Faker::Name.name }
Comment.blueprint do
author { Sham.name } # Set the author's name to a random name.
end
Sham takes the random names generated by Faker and ensures two things:
- You will get the same sequence of names every time you run a test.
- You won't get the same name twice.
To ensure that you get repeatable values, you have to reset Sham before every test or spec.
If you're using Test::Unit, add this to your test_helper.rb:
class Test::Unit::TestCase
setup { Sham.reset }
end
If you're using RSpec, add this to your spec_helper.rb:
Spec::Runner.configure do |config|
config.before(:each) { Sham.reset }
end
script/plugin install git://github.com/notahat/machinist.git
Copyright (c) 2008 Peter Yandell, released under the MIT license