Instantly share code, notes, and snippets.

Embed
What would you like to do?
FactoryDefault: re-use associated objects in factories
module FactoryDefault
module CreateDefaultMethod
def create_default(name, *args, &block)
res = create(name, *args, &block)
FactoryDefault.register(name, res)
res
end
end
module RunnerExt
refine FactoryGirl::FactoryRunner do
def name
@name
end
end
end
using RunnerExt
module StrategyExt
def association(runner)
return super unless FactoryDefault.exists?(runner.name)
FactoryDefault.get(runner.name)
end
end
class << self
def init
FactoryGirl::Syntax::Methods.include CreateDefaultMethod
FactoryGirl::Strategy::Create.prepend StrategyExt
FactoryGirl::Strategy::Build.prepend StrategyExt
FactoryGirl::Strategy::Stub.prepend StrategyExt
end
def register(name, obj)
store[name] = obj
end
def get(name)
store[name]
end
def exists?(name)
store.key?(name)
end
def remove(name)
store.delete(name)
end
def reset
@store = nil
end
private
def store
@store ||= {}
end
end
end
if ENV['FD']
FactoryDefault.init
RSpec.configure do |config|
config.after(:each) { FactoryDefault.reset }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment