Module: TestProf::LetItBe

Defined in:
lib/test_prof/recipes/rspec/let_it_be.rb

Overview

Just like ‘let`, but persist the result for the whole group. NOTE: Experimental and magical, for more control use `before_all`.

Constant Summary collapse

PREFIX =

Use uniq prefix for instance variables to avoid collisions We want to use the power of Ruby’s unicode support) And we love cats!)

RUBY_ENGINE == "jruby" ? "@__jruby_is_not_cat_friendly__" : "@😸"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.module_for(group) ⇒ Object



11
12
13
14
15
# File 'lib/test_prof/recipes/rspec/let_it_be.rb', line 11

def module_for(group)
  modules[group] ||= begin
    Module.new.tap { |mod| group.prepend(mod) }
  end
end

Instance Method Details

#define_let_it_be_methods(identifier, reload: false, refind: false) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/test_prof/recipes/rspec/let_it_be.rb', line 42

def define_let_it_be_methods(identifier, reload: false, refind: false)
  let_accessor = -> { instance_variable_get(:"#{PREFIX}#{identifier}") }

  if reload
    let_accessor = lambda do
      record = instance_variable_get(:"#{PREFIX}#{identifier}")
      next unless record.is_a?(::ActiveRecord::Base)
      record.reload
    end
  end

  if refind
    let_accessor = lambda do
      record = instance_variable_get(:"#{PREFIX}#{identifier}")
      next unless record.is_a?(::ActiveRecord::Base)

      record.class.find(record.send(record.class.primary_key))
    end
  end

  LetItBe.module_for(self).module_eval do
    define_method(identifier) do
      # Trying to detect the context (couldn't find other way so far)
      if /\(:context\)/.match?(@__inspect_output)
        instance_variable_get(:"#{PREFIX}#{identifier}")
      else
        # Fallback to let definition
        super()
      end
    end
  end

  let(identifier, &let_accessor)
end

#let_it_be(identifier, **options, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/test_prof/recipes/rspec/let_it_be.rb', line 28

def let_it_be(identifier, **options, &block)
  initializer = proc do
    instance_variable_set(:"#{PREFIX}#{identifier}", instance_exec(&block))
  end

  if within_before_all?
    within_before_all(&initializer)
  else
    before_all(&initializer)
  end

  define_let_it_be_methods(identifier, **options)
end