Skip to content

Instantly share code, notes, and snippets.

@foca
Created November 28, 2010 01:17
Show Gist options
  • Save foca/718471 to your computer and use it in GitHub Desktop.
Save foca/718471 to your computer and use it in GitHub Desktop.
All factory libraries are overengineered.
require "ffaker"
class ActiveRecord::Base
def self.define_factory(name=nil, parent=nil, &block)
name = [name, "factory"].compact.join("_")
scope name, lambda { |overrides={}|
parent ||= scoped
attributes = instance_eval(&block).merge(overrides)
parent.where(attributes)
}
end
end
User.class_eval do
define_factory {{
first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name,
email: Faker::Internet.email,
password: "monkey",
password_confirmation: "monkey"
}}
end
Comment.class_eval do
define_factory {{
title: Faker::Lorem.sentence,
body: Faker::Lorem.paragraph
}}
end
# In order to support associations you *have* to be explicit.
# Yeah, it's not as magic as FG or Machinist, but it works fine.
#
# And I haven't worked in project with such a complex dependency graph
# that requires you to write a lot of associations by hand (maybe it's
# just me.)
#
# Finally, this is WAY faster than any other factory lib out there,
# except for database fixtures. Well, I haven't benchmarked it, but
# I'm pretty sure it is :P
#
# Go ahead and benchmark it if you want, I'd like to see the results.
comment = Comment.factory.create(title: "My Comment") do |c|
c.commenter = User.factory.create
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment