Module: Gitlab::Experiment::RSpecHelpers

Defined in:
lib/gitlab/experiment/rspec.rb

Instance Method Summary collapse

Instance Method Details

#stub_experiments(experiments, times = nil) ⇒ Object



6
7
8
# File 'lib/gitlab/experiment/rspec.rb', line 6

def stub_experiments(experiments, times = nil)
  experiments.each { |experiment| wrapped_experiment(experiment, times) }
end

#wrapped_experiment(experiment, times = nil, expected = false, &block) ⇒ Object



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
# File 'lib/gitlab/experiment/rspec.rb', line 10

def wrapped_experiment(experiment, times = nil, expected = false, &block)
  klass, experiment_name, variant_name = *experiment_details(experiment)
  base_klass = Configuration.base_class.constantize

  # Set expectations on experiment classes so we can and_wrap_original with more specific args
  experiment_klasses = base_klass.descendants.reject { |k| k == klass }
  experiment_klasses.push(base_klass).each do |k|
    allow(k).to receive(:new).and_call_original
  end

  receiver = receive(:new)

  # Be specific for BaseClass calls
  receiver = receiver.with(experiment_name, any_args) if experiment_name && klass == base_klass

  receiver.exactly(times).times if times

  # Set expectations on experiment class of interest
  allow_or_expect_klass = expected ? expect(klass) : allow(klass)
  allow_or_expect_klass.to receiver.and_wrap_original do |method, *original_args, &original_block|
    method.call(*original_args).tap do |e|
      # Stub internal methods before calling the original_block
      allow(e).to receive(:enabled?).and_return(true)

      if variant_name == true # passing true allows the rollout to do its job
        allow(e).to receive(:experiment_group?).and_return(true)
      else
        allow(e).to receive(:resolve_variant_name).and_return(variant_name.to_s)
      end

      # Stub/set expectations before calling the original_block
      yield e if block

      original_block.call(e) if original_block.present?
    end
  end
end