Last active
September 17, 2016 18:33
-
-
Save stephencelis/273579 to your computer and use it in GitHub Desktop.
factory_girl for minitest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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