Skip to content

Instantly share code, notes, and snippets.

@stephencelis
Last active September 17, 2016 18:33
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
  • Save stephencelis/273579 to your computer and use it in GitHub Desktop.
Save stephencelis/273579 to your computer and use it in GitHub Desktop.
factory_girl for minitest
# factory_girl for minitest
#
# Factory.define :user do |f|
# f.login 'johndoe%d' # Sequence.
# f.email '%{login}@example.com' # Interpolate.
# f.password f.password_confirmation('foobar') # Chain.
# end
#
# Factory.define :post do |f|
# f.user { Factory :user } # Blocks, if you must.
# end
class Minifacture < Struct.new(:__klass__)
undef_method *instance_methods.grep(/^(?!__|object_id)/) # BlankerSlate.
@@factories = {} and private_class_method :new
class << self
def define(name)
@@factories[name = name.to_s] = {} and yield new(name)
end
def build(name, attrs = {})
(name, n = name.to_s) and (m = name.classify.constantize).new do |rec|
attrs.symbolize_keys!.reverse_update(@@factories[name]).each do |k, v|
rec.send "#{k}=", case v when String # Sequence and interpolate.
v.sub(/%\d*d/) {|d| d % n ||= m.maximum(:id).to_i + 1} % attrs % n
when Proc then v.call(rec) else v
end
end
end
end
def create(name, attrs = {})
build(name, attrs).tap { |record| record.save! }
end
end
def method_missing(name, value = nil, &block)
@@factories[__klass__][name] = block || value
end
end
def Minifacture(name, attrs = {})s
Minifacture.create(name, attrs)
end
Factory = Minifacture
alias Factory Minifacture
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment