assaf / vanity

Experiment Driven Development for Ruby
http://vanity.labnotes.org
MIT License
1.55k stars 269 forks source link

Be able to disable vanity for test. #375

Open frostmark opened 2 years ago

frostmark commented 2 years ago

Would be nice to have the ability to disable vanity and get false by default for all experiments

bensheldon commented 2 years ago

As a starting place, here are the test helpers that I include in projects (The VanityDispatcher object is described in #379):

module VanityHelpers
  def vanity_stub_choice(vanity_id:, experiment_id:, choice:)
    @stubbed_experiments.add(experiment_id)
    VanityDispatcher.new(vanity_id).within_context do
      Vanity.playground.experiments[experiment_id].chooses(choice)
    end
  end

  def vanity_stub_choice_for_everyone(experiment_id:, choice:)
    @global_vanity_ab_test_stubs[experiment_id] = choice
  end

  def vanity_reset
    @use_real_vanity = false
    @stubbed_experiments = Set.new
    @global_vanity_ab_test_stubs = {}
  end

  def vanity_use_real_ab_test?(experiment_id)
    @use_real_vanity || @stubbed_experiments.include?(experiment_id)
  end

  def vanity_unstub_ab_test
    @use_real_vanity = true
  end
end

RSpec.configure do |config|
  config.include VanityHelpers

  config.before do
    vanity_reset
    allow(Vanity).to receive(:ab_test).and_wrap_original do |m, *args|
      if vanity_use_real_ab_test?(args[0])
        m.call(*args)
      else
        @global_vanity_ab_test_stubs[args[0]]
      end
    end
  end
end