Skip to content

Instantly share code, notes, and snippets.

@notahat
Created June 6, 2009 02:59
Show Gist options
  • Save notahat/124652 to your computer and use it in GitHub Desktop.
Save notahat/124652 to your computer and use it in GitHub Desktop.
Example of how Machinist handles model associations
# Let's say we have some really simple models for a blog. (I'm using
# DataMapper here, but Machinist works exactly the same way with ActiveRecord.)
class Person
include DataMapper::Resource
property :id, Serial
property :name, String
end
class Post
include DataMapper::Resource
property :id, Serial
property :author_id, Integer
property :body, String
belongs_to :author, :class_name => "Person", :child_key => [:author_id]
has n, :comments
end
class Comment
include DataMapper::Resource
property :id, Serial
property :post_id, Integer
property :body, String
belongs_to :post
end
# I can define Machinist blueprints for these like this:
Person.blueprint do
name "Fred" # In real life I'd use Sham to generate the attribute values.
# See the Machinist README for details!
end
Post.blueprint do
author # This tells Machinist to make an author for the post.
body "A post"
end
Comment.blueprint do
post # This tells Machinist to make a post for the comment.
body "A comment"
end
# Then in my tests I can call:
comment = Comment.make
# Machinist will introspect on the associations and create a Comment, a Post,
# and a Person, and set up all the relationships properly.
#
# Let's see Factory Girl do that! ;)
#
# Machinist lives at: http://github.com/notahat/machinist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment