Skip to content

Instantly share code, notes, and snippets.

@jacquescrocker
Created February 23, 2011 01:01
Show Gist options
  • Save jacquescrocker/839788 to your computer and use it in GitHub Desktop.
Save jacquescrocker/839788 to your computer and use it in GitHub Desktop.
monkey patch for fabrication gem that allows Fabricate.unique (for mongoid only at the moment). just require this file within config/environments/test.rb and it should work
class Fabricate
class << self
def unique(name, overrides={}, &block)
schematic = Fabrication::Fabricator.schematics[name]
raise Fabrication::UnfabricatableError, "No fabricator found for '#{name}'" unless schematic
# pull out the fabricator_id
fabricator_id = overrides[:fabricator_id] || schematic.attribute(:fabricator_id) || name
# set the overriden fabricator_id
overrides[:fabricator_id] = fabricator_id
# see if there's already a match with that fabricator_id
existing = schematic.klass.where(:fabricator_id => fabricator_id.to_s).first
if existing
attributes = Fabrication::Fabricator.generate(name, {
:save => false, :attributes => true
}, overrides, &block)
existing.update_attributes!(attributes)
existing
else
Fabrication::Fabricator.generate(name, {
:save => true
}, overrides, &block)
end
end
end
end
# mongoid helpers adds fabricator_id field and a class level fabricated? helper
module Fabrication
module Mongoid
module Helpers
extend ActiveSupport::Concern
included do
# field gets included for any model defined by fabricator
field :fabricator_id, :type => String
end
module ClassMethods
def fabricated?(id)
where(:fabricator_id => id.to_s).count > 0
end
end
end
end
end
# includes helpers within the default Mongoid::Document
module Mongoid
module Document
include Fabrication::Mongoid::Helpers
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment