Skip to content

Instantly share code, notes, and snippets.

@sobrinho
Last active December 10, 2018 16:27
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sobrinho/2901172 to your computer and use it in GitHub Desktop.
Save sobrinho/2901172 to your computer and use it in GitHub Desktop.
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