File: fabrication_patch.rb

package info (click to toggle)
ruby-test-prof 1.5.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 660 kB
  • sloc: ruby: 6,064; makefile: 4
file content (60 lines) | stat: -rw-r--r-- 1,671 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# frozen_string_literal: true

module TestProf
  module FactoryDefault # :nodoc: all
    module FabricationPatch
      module DefaultExt
        def create_default(name, overrides = {}, &block)
          obj = ::Fabricate.create(name, overrides, &block)
          set_fabricate_default(name, obj)
        end

        def set_fabricate_default(name, obj, **opts)
          FactoryDefault.register(
            name, obj,
            preserve_attributes: FactoryDefault.config.preserve_attributes,
            preserve_traits: FactoryDefault.config.preserve_traits,
            **opts
          )
        end

        def get_fabricate_default(name, **overrides)
          FactoryDefault.get(name, nil, overrides, skip_stats: true)
        end

        def skip_fabricate_default(&block)
          FactoryDefault.disable!(&block)
        end

        def create(name, overrides = {}, &block)
          self.fabrication_depth += 1
          # We do not support defaults for objects created with attribute blocks
          return super if block

          return super if fabrication_depth < 2

          FactoryDefault.get(name, nil, overrides, **{}) ||
            FactoryDefault.profiler.instrument(name, nil, overrides) { super }
        ensure
          self.fabrication_depth -= 1
        end

        private

        def fabrication_depth
          Thread.current[:_fab_depth_] ||= 0
        end

        def fabrication_depth=(value)
          Thread.current[:_fab_depth_] = value
        end
      end

      def self.patch
        TestProf.require "fabrication" do
          ::Fabricate.singleton_class.prepend(DefaultExt)
        end
      end
    end
  end
end