Module: Gitlab::Experiment::RSpecHelpers

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

Instance Method Summary collapse

Instance Method Details

#stub_experiments(experiments) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/gitlab/experiment/rspec.rb', line 6

def stub_experiments(experiments)
  experiments.each do |name, variant|
    variant = :control if variant == false
    raise ArgumentError, 'variant must be a symbol or false' unless variant.is_a?(Symbol)

    klass = Gitlab::Experiment.send(:constantize, name) # rubocop:disable GitlabSecurity/PublicSend

    # We have to use this high level any_instance behavior as there's
    # not an alternative that allows multiple wrappings of `new`.
    allow_any_instance_of(klass).to receive(:enabled?).and_return(true)
    allow_any_instance_of(klass).to receive(:resolve_variant_name).and_return(variant.to_s)
  end
end

#wrapped_experiment(experiment, shallow: false, failure: nil, &block) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/gitlab/experiment/rspec.rb', line 20

def wrapped_experiment(experiment, shallow: false, failure: nil, &block)
  if shallow
    yield experiment if block.present?
    return experiment
  end

  receive_wrapped_new = receive(:new).and_wrap_original do |new, *new_args, &new_block|
    instance = new.call(*new_args)
    instance.tap(&block) if block.present?
    instance.tap(&new_block) if new_block.present?
    instance
  end

  klass = experiment.class == Class ? experiment : experiment.class
  if failure
    expect(klass).to receive_wrapped_new, failure
  else
    allow(klass).to receive_wrapped_new
  end
end