Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Object caching for factory girl
module FactoryGirl
module Strategy
class Cache
def association(runner)
runner.run(:cache)
end
def result(evaluation)
repository.read(evaluation) || repository.store(evaluation)
end
protected
def repository
Repository.instance
end
end
class Repository
include Singleton
def initialize
recycle!
end
def recycle!
@repository = Hash.new { |hash, key| hash[key] = {} }
end
def read(evaluation)
repository[evaluation.object.class][evaluation.object.attributes]
end
def store(evaluation)
repository[evaluation.object.class][evaluation.object.attributes] = evaluation.object.tap do |object|
evaluation.notify(:after_build, object)
evaluation.notify(:before_create, object)
evaluation.create(object)
evaluation.notify(:after_create, object)
end
end
protected
attr_reader :repository
end
end
end
FactoryGirl.register_strategy(:cache, FactoryGirl::Strategy::Cache)
RSpec.configure do |config|
config.after do
FactoryGirl::Strategy::Repository.instance.recycle!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment