Module: FactoryBot::AnyInstance

Defined in:
lib/factory_bot_any_instance.rb

Overview

This module adds helper methods to FactoryBot to memoize instances created by factories.

Instance Method Summary collapse

Instance Method Details

#any(factory_name) ⇒ Object

Create or return an instance of the specified factory. If this method has been called previously with the same factory name, then the previously created instance will be returned. Otherwise a new instance will be created using all the default factory settings and stored until clear_instances is called.



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/factory_bot_any_instance.rb', line 11

def any(factory_name)
  factory_name = factory_name.to_sym
  instance = any_instances[factory_name]
  unless instance
    instance = FactoryBot.create(factory_name)
    @any_instance_lock.synchronize do
      @any_instances[factory_name] = instance
    end
  end
  instance
end

#clear_instancesObject

Clear all the memoized instances. Instances are kept in a global namespace and must be cleared between test runs.



25
26
27
28
29
# File 'lib/factory_bot_any_instance.rb', line 25

def clear_instances
  if defined?(@any_instances) && @any_instances
    @any_instances = {}
  end
end