Search is not available for this dataset
id
stringlengths 1
8
| text
stringlengths 72
9.81M
| addition_count
int64 0
10k
| commit_subject
stringlengths 0
3.7k
| deletion_count
int64 0
8.43k
| file_extension
stringlengths 0
32
| lang
stringlengths 1
94
| license
stringclasses 10
values | repo_name
stringlengths 9
59
|
---|---|---|---|---|---|---|---|---|
10071350 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
@control ||= anything
@alternatives ||= anything
@times ||= 1
actual.should_receive(:experiment_variable).with(@alternatives, @control, name).exactly(@times).times
end
chain :with do |control, alternatives|
@control = control
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Bug in spec expectation
`*alternatives` is always an array, even if one argument.
<DFF> @@ -584,7 +584,7 @@ describe Split::Helper do
@control ||= anything
@alternatives ||= anything
@times ||= 1
- actual.should_receive(:experiment_variable).with(@alternatives, @control, name).exactly(@times).times
+ actual.should_receive(:experiment_variable).with([@alternatives].flatten, @control, name).exactly(@times).times
end
chain :with do |control, alternatives|
@control = control
| 1 | Bug in spec expectation | 1 | .rb | rb | mit | splitrb/split |
10071351 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
@control ||= anything
@alternatives ||= anything
@times ||= 1
actual.should_receive(:experiment_variable).with(@alternatives, @control, name).exactly(@times).times
end
chain :with do |control, alternatives|
@control = control
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Bug in spec expectation
`*alternatives` is always an array, even if one argument.
<DFF> @@ -584,7 +584,7 @@ describe Split::Helper do
@control ||= anything
@alternatives ||= anything
@times ||= 1
- actual.should_receive(:experiment_variable).with(@alternatives, @control, name).exactly(@times).times
+ actual.should_receive(:experiment_variable).with([@alternatives].flatten, @control, name).exactly(@times).times
end
chain :with do |control, alternatives|
@control = control
| 1 | Bug in spec expectation | 1 | .rb | rb | mit | splitrb/split |
10071352 | <NME> spec_helper.rb
<BEF> # frozen_string_literal: true
ENV["RACK_ENV"] = "test"
require "rubygems"
require "bundler/setup"
require "simplecov"
SimpleCov.start
require "split"
require "ostruct"
require "yaml"
Dir["./spec/support/*.rb"].each { |f| require f }
module GlobalSharedContext
extend RSpec::SharedContext
let(:mock_user) { Split::User.new(double(session: {})) }
before(:each) do
Split.configuration = Split::Configuration.new
Split.redis = Redis.new
Split.redis.select(10)
Split.redis.flushdb
Split::Cache.clear
@ab_user = mock_user
@params = nil
end
end
end
def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27')
r = OpenStruct.new
r.user_agent = ua
r.ip = '192.168.1.1'
@request ||= r
end
def params
@params ||= {}
end
def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27")
@request ||= begin
r = OpenStruct.new
r.user_agent = ua
r.ip = "192.168.1.1"
r
end
end
<MSG> Merge pull request #304 from ipoval/code-gardening
[code gardening] minor memoization fix in spec; trim trailing whitespace...
<DFF> @@ -32,8 +32,10 @@ def params
end
def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27')
- r = OpenStruct.new
- r.user_agent = ua
- r.ip = '192.168.1.1'
- @request ||= r
+ @request ||= begin
+ r = OpenStruct.new
+ r.user_agent = ua
+ r.ip = '192.168.1.1'
+ r
+ end
end
| 6 | Merge pull request #304 from ipoval/code-gardening | 4 | .rb | rb | mit | splitrb/split |
10071353 | <NME> spec_helper.rb
<BEF> # frozen_string_literal: true
ENV["RACK_ENV"] = "test"
require "rubygems"
require "bundler/setup"
require "simplecov"
SimpleCov.start
require "split"
require "ostruct"
require "yaml"
Dir["./spec/support/*.rb"].each { |f| require f }
module GlobalSharedContext
extend RSpec::SharedContext
let(:mock_user) { Split::User.new(double(session: {})) }
before(:each) do
Split.configuration = Split::Configuration.new
Split.redis = Redis.new
Split.redis.select(10)
Split.redis.flushdb
Split::Cache.clear
@ab_user = mock_user
@params = nil
end
end
end
def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27')
r = OpenStruct.new
r.user_agent = ua
r.ip = '192.168.1.1'
@request ||= r
end
def params
@params ||= {}
end
def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27")
@request ||= begin
r = OpenStruct.new
r.user_agent = ua
r.ip = "192.168.1.1"
r
end
end
<MSG> Merge pull request #304 from ipoval/code-gardening
[code gardening] minor memoization fix in spec; trim trailing whitespace...
<DFF> @@ -32,8 +32,10 @@ def params
end
def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27')
- r = OpenStruct.new
- r.user_agent = ua
- r.ip = '192.168.1.1'
- @request ||= r
+ @request ||= begin
+ r = OpenStruct.new
+ r.user_agent = ua
+ r.ip = '192.168.1.1'
+ r
+ end
end
| 6 | Merge pull request #304 from ipoval/code-gardening | 4 | .rb | rb | mit | splitrb/split |
10071354 | <NME> spec_helper.rb
<BEF> # frozen_string_literal: true
ENV["RACK_ENV"] = "test"
require "rubygems"
require "bundler/setup"
require "simplecov"
SimpleCov.start
require "split"
require "ostruct"
require "yaml"
Dir["./spec/support/*.rb"].each { |f| require f }
module GlobalSharedContext
extend RSpec::SharedContext
let(:mock_user) { Split::User.new(double(session: {})) }
before(:each) do
Split.configuration = Split::Configuration.new
Split.redis = Redis.new
Split.redis.select(10)
Split.redis.flushdb
Split::Cache.clear
@ab_user = mock_user
@params = nil
end
end
end
def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27')
r = OpenStruct.new
r.user_agent = ua
r.ip = '192.168.1.1'
@request ||= r
end
def params
@params ||= {}
end
def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27")
@request ||= begin
r = OpenStruct.new
r.user_agent = ua
r.ip = "192.168.1.1"
r
end
end
<MSG> Merge pull request #304 from ipoval/code-gardening
[code gardening] minor memoization fix in spec; trim trailing whitespace...
<DFF> @@ -32,8 +32,10 @@ def params
end
def request(ua = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27')
- r = OpenStruct.new
- r.user_agent = ua
- r.ip = '192.168.1.1'
- @request ||= r
+ @request ||= begin
+ r = OpenStruct.new
+ r.user_agent = ua
+ r.ip = '192.168.1.1'
+ r
+ end
end
| 6 | Merge pull request #304 from ipoval/code-gardening | 4 | .rb | rb | mit | splitrb/split |
10071355 | <NME> helper.rb
<BEF> # frozen_string_literal: true
module Split
module Helper
OVERRIDE_PARAM_NAME = "ab_test"
module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives)
alternative = if Split.configuration.enabled && !exclude_visitor?
experiment.save
raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil?
trial = Trial.new(user: ab_user, experiment: experiment,
override: override_alternative(experiment.name), exclude: exclude_visitor?,
disabled: split_generically_disabled?)
alt = trial.choose!(self)
alt ? alt.name : nil
else
control_variable(experiment.control)
end
rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
if Split.configuration.db_failover_allow_parameter_override
alternative = override_alternative(experiment.name) if override_present?(experiment.name)
alternative = control_variable(experiment.control) if split_generically_disabled?
end
ensure
alternative ||= control_variable(experiment.control)
end
if block_given?
metadata = experiment.metadata[alternative] if experiment.metadata
yield(alternative, metadata || {})
else
alternative
end
end
def reset!(experiment)
ab_user.delete(experiment.key)
end
def finish_experiment(experiment, options = { reset: true })
return false if active_experiments[experiment.name].nil?
return true if experiment.has_winner?
should_reset = experiment.resettable? && options[:reset]
if ab_user[experiment.finished_key] && !should_reset
true
else
alternative_name = ab_user[experiment.key]
trial = Trial.new(
user: ab_user,
experiment: experiment,
alternative: alternative_name,
goals: options[:goals],
)
trial.complete!(self)
if should_reset
reset!(experiment)
else
ab_user[experiment.finished_key] = true
end
end
end
def ab_finished(metric_descriptor, options = { reset: true })
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, goals = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
next if override_present?(experiment.key)
finish_experiment(experiment, options.merge(goals: goals))
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_record_extra_info(metric_descriptor, key, value = 1)
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, _ = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
alternative_name = ab_user[experiment.key]
if alternative_name
alternative = experiment.alternatives.find { |alt| alt.name == alternative_name }
alternative.record_extra_info(key, value) if alternative
end
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_active_experiments
ab_user.active_experiments
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def override_present?(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
end
def exclude_visitor?
instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?
end
def is_robot?
if request.cookies && request.cookies.key?("split_override")
experiments = JSON.parse(request.cookies["split_override"]) rescue {}
experiments[experiment_name]
end
end
def split_generically_disabled?
defined?(params) && params["SPLIT_DISABLE"]
end
def ab_user
@ab_user ||= User.new(self)
end
def exclude_visitor?
defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
defined?(request) && request.user_agent =~ Split.configuration.robot_regex
end
def is_preview?
defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview"
end
def is_ignored_ip_address?
return false if Split.configuration.ignore_ip_addresses.empty?
Split.configuration.ignore_ip_addresses.each do |ip|
return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip))
end
false
end
def active_experiments
ab_user.active_experiments
end
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
goals = Array(metric_descriptor.values.first)
else
experiment_name = metric_descriptor
goals = []
end
return experiment_name, goals
end
def control_variable(control)
Hash === control ? control.keys.first.to_s : control.to_s
end
end
end
<MSG> Checks for defined?(request) on Helper#exclude_visitor?
<DFF> @@ -122,7 +122,7 @@ module Split
end
def exclude_visitor?
- instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?
+ defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
| 1 | Checks for defined?(request) on Helper#exclude_visitor? | 1 | .rb | rb | mit | splitrb/split |
10071356 | <NME> helper.rb
<BEF> # frozen_string_literal: true
module Split
module Helper
OVERRIDE_PARAM_NAME = "ab_test"
module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives)
alternative = if Split.configuration.enabled && !exclude_visitor?
experiment.save
raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil?
trial = Trial.new(user: ab_user, experiment: experiment,
override: override_alternative(experiment.name), exclude: exclude_visitor?,
disabled: split_generically_disabled?)
alt = trial.choose!(self)
alt ? alt.name : nil
else
control_variable(experiment.control)
end
rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
if Split.configuration.db_failover_allow_parameter_override
alternative = override_alternative(experiment.name) if override_present?(experiment.name)
alternative = control_variable(experiment.control) if split_generically_disabled?
end
ensure
alternative ||= control_variable(experiment.control)
end
if block_given?
metadata = experiment.metadata[alternative] if experiment.metadata
yield(alternative, metadata || {})
else
alternative
end
end
def reset!(experiment)
ab_user.delete(experiment.key)
end
def finish_experiment(experiment, options = { reset: true })
return false if active_experiments[experiment.name].nil?
return true if experiment.has_winner?
should_reset = experiment.resettable? && options[:reset]
if ab_user[experiment.finished_key] && !should_reset
true
else
alternative_name = ab_user[experiment.key]
trial = Trial.new(
user: ab_user,
experiment: experiment,
alternative: alternative_name,
goals: options[:goals],
)
trial.complete!(self)
if should_reset
reset!(experiment)
else
ab_user[experiment.finished_key] = true
end
end
end
def ab_finished(metric_descriptor, options = { reset: true })
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, goals = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
next if override_present?(experiment.key)
finish_experiment(experiment, options.merge(goals: goals))
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_record_extra_info(metric_descriptor, key, value = 1)
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, _ = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
alternative_name = ab_user[experiment.key]
if alternative_name
alternative = experiment.alternatives.find { |alt| alt.name == alternative_name }
alternative.record_extra_info(key, value) if alternative
end
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_active_experiments
ab_user.active_experiments
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def override_present?(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
end
def exclude_visitor?
instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?
end
def is_robot?
if request.cookies && request.cookies.key?("split_override")
experiments = JSON.parse(request.cookies["split_override"]) rescue {}
experiments[experiment_name]
end
end
def split_generically_disabled?
defined?(params) && params["SPLIT_DISABLE"]
end
def ab_user
@ab_user ||= User.new(self)
end
def exclude_visitor?
defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
defined?(request) && request.user_agent =~ Split.configuration.robot_regex
end
def is_preview?
defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview"
end
def is_ignored_ip_address?
return false if Split.configuration.ignore_ip_addresses.empty?
Split.configuration.ignore_ip_addresses.each do |ip|
return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip))
end
false
end
def active_experiments
ab_user.active_experiments
end
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
goals = Array(metric_descriptor.values.first)
else
experiment_name = metric_descriptor
goals = []
end
return experiment_name, goals
end
def control_variable(control)
Hash === control ? control.keys.first.to_s : control.to_s
end
end
end
<MSG> Checks for defined?(request) on Helper#exclude_visitor?
<DFF> @@ -122,7 +122,7 @@ module Split
end
def exclude_visitor?
- instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?
+ defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
| 1 | Checks for defined?(request) on Helper#exclude_visitor? | 1 | .rb | rb | mit | splitrb/split |
10071357 | <NME> helper.rb
<BEF> # frozen_string_literal: true
module Split
module Helper
OVERRIDE_PARAM_NAME = "ab_test"
module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives)
alternative = if Split.configuration.enabled && !exclude_visitor?
experiment.save
raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil?
trial = Trial.new(user: ab_user, experiment: experiment,
override: override_alternative(experiment.name), exclude: exclude_visitor?,
disabled: split_generically_disabled?)
alt = trial.choose!(self)
alt ? alt.name : nil
else
control_variable(experiment.control)
end
rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
if Split.configuration.db_failover_allow_parameter_override
alternative = override_alternative(experiment.name) if override_present?(experiment.name)
alternative = control_variable(experiment.control) if split_generically_disabled?
end
ensure
alternative ||= control_variable(experiment.control)
end
if block_given?
metadata = experiment.metadata[alternative] if experiment.metadata
yield(alternative, metadata || {})
else
alternative
end
end
def reset!(experiment)
ab_user.delete(experiment.key)
end
def finish_experiment(experiment, options = { reset: true })
return false if active_experiments[experiment.name].nil?
return true if experiment.has_winner?
should_reset = experiment.resettable? && options[:reset]
if ab_user[experiment.finished_key] && !should_reset
true
else
alternative_name = ab_user[experiment.key]
trial = Trial.new(
user: ab_user,
experiment: experiment,
alternative: alternative_name,
goals: options[:goals],
)
trial.complete!(self)
if should_reset
reset!(experiment)
else
ab_user[experiment.finished_key] = true
end
end
end
def ab_finished(metric_descriptor, options = { reset: true })
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, goals = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
next if override_present?(experiment.key)
finish_experiment(experiment, options.merge(goals: goals))
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_record_extra_info(metric_descriptor, key, value = 1)
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, _ = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
if experiments.any?
experiments.each do |experiment|
alternative_name = ab_user[experiment.key]
if alternative_name
alternative = experiment.alternatives.find { |alt| alt.name == alternative_name }
alternative.record_extra_info(key, value) if alternative
end
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_active_experiments
ab_user.active_experiments
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def override_present?(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
end
def exclude_visitor?
instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?
end
def is_robot?
if request.cookies && request.cookies.key?("split_override")
experiments = JSON.parse(request.cookies["split_override"]) rescue {}
experiments[experiment_name]
end
end
def split_generically_disabled?
defined?(params) && params["SPLIT_DISABLE"]
end
def ab_user
@ab_user ||= User.new(self)
end
def exclude_visitor?
defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
defined?(request) && request.user_agent =~ Split.configuration.robot_regex
end
def is_preview?
defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview"
end
def is_ignored_ip_address?
return false if Split.configuration.ignore_ip_addresses.empty?
Split.configuration.ignore_ip_addresses.each do |ip|
return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip))
end
false
end
def active_experiments
ab_user.active_experiments
end
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
goals = Array(metric_descriptor.values.first)
else
experiment_name = metric_descriptor
goals = []
end
return experiment_name, goals
end
def control_variable(control)
Hash === control ? control.keys.first.to_s : control.to_s
end
end
end
<MSG> Checks for defined?(request) on Helper#exclude_visitor?
<DFF> @@ -122,7 +122,7 @@ module Split
end
def exclude_visitor?
- instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?
+ defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
| 1 | Checks for defined?(request) on Helper#exclude_visitor? | 1 | .rb | rb | mit | splitrb/split |
10071358 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
module Split
class Experiment
attr_accessor :name
attr_accessor :goals
attr_accessor :alternative_probabilities
attr_accessor :metadata
attr_reader :alternatives
attr_reader :resettable
DEFAULT_OPTIONS = {
resettable: true
}
def self.find(name)
Split.cache(:experiments, name) do
return unless Split.redis.exists?(name)
Experiment.new(name).tap { |exp| exp.load_from_redis }
end
end
def initialize(name, options = {})
options = DEFAULT_OPTIONS.merge(options)
@name = name.to_s
extract_alternatives_from_options(options)
end
def self.finished_key(key)
"#{key}:finished"
end
def set_alternatives_and_options(options)
options_with_defaults = DEFAULT_OPTIONS.merge(
options.reject { |k, v| v.nil? }
)
self.alternatives = options_with_defaults[:alternatives]
self.goals = options_with_defaults[:goals]
self.resettable = options_with_defaults[:resettable]
self.algorithm = options_with_defaults[:algorithm]
self.metadata = options_with_defaults[:metadata]
end
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
if alts[0].is_a? Hash
alts = alts[0].map { |k, v| { k => v } }
end
end
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration
options[:metadata] = load_metadata_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
end
redis.hmset(experiment_config_key, :resettable, resettable.to_s,
:algorithm, algorithm.to_s)
self
end
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub('/', '--')
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Fix Layout/ElseAlignment
<DFF> @@ -393,7 +393,7 @@ module Split
def jstring(goal = nil)
js_id = if goal.nil?
name
- else
+ else
name + "-" + goal
end
js_id.gsub('/', '--')
| 1 | Fix Layout/ElseAlignment | 1 | .rb | rb | mit | splitrb/split |
10071359 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
module Split
class Experiment
attr_accessor :name
attr_accessor :goals
attr_accessor :alternative_probabilities
attr_accessor :metadata
attr_reader :alternatives
attr_reader :resettable
DEFAULT_OPTIONS = {
resettable: true
}
def self.find(name)
Split.cache(:experiments, name) do
return unless Split.redis.exists?(name)
Experiment.new(name).tap { |exp| exp.load_from_redis }
end
end
def initialize(name, options = {})
options = DEFAULT_OPTIONS.merge(options)
@name = name.to_s
extract_alternatives_from_options(options)
end
def self.finished_key(key)
"#{key}:finished"
end
def set_alternatives_and_options(options)
options_with_defaults = DEFAULT_OPTIONS.merge(
options.reject { |k, v| v.nil? }
)
self.alternatives = options_with_defaults[:alternatives]
self.goals = options_with_defaults[:goals]
self.resettable = options_with_defaults[:resettable]
self.algorithm = options_with_defaults[:algorithm]
self.metadata = options_with_defaults[:metadata]
end
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
if alts[0].is_a? Hash
alts = alts[0].map { |k, v| { k => v } }
end
end
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration
options[:metadata] = load_metadata_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
end
redis.hmset(experiment_config_key, :resettable, resettable.to_s,
:algorithm, algorithm.to_s)
self
end
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub('/', '--')
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Fix Layout/ElseAlignment
<DFF> @@ -393,7 +393,7 @@ module Split
def jstring(goal = nil)
js_id = if goal.nil?
name
- else
+ else
name + "-" + goal
end
js_id.gsub('/', '--')
| 1 | Fix Layout/ElseAlignment | 1 | .rb | rb | mit | splitrb/split |
10071360 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
module Split
class Experiment
attr_accessor :name
attr_accessor :goals
attr_accessor :alternative_probabilities
attr_accessor :metadata
attr_reader :alternatives
attr_reader :resettable
DEFAULT_OPTIONS = {
resettable: true
}
def self.find(name)
Split.cache(:experiments, name) do
return unless Split.redis.exists?(name)
Experiment.new(name).tap { |exp| exp.load_from_redis }
end
end
def initialize(name, options = {})
options = DEFAULT_OPTIONS.merge(options)
@name = name.to_s
extract_alternatives_from_options(options)
end
def self.finished_key(key)
"#{key}:finished"
end
def set_alternatives_and_options(options)
options_with_defaults = DEFAULT_OPTIONS.merge(
options.reject { |k, v| v.nil? }
)
self.alternatives = options_with_defaults[:alternatives]
self.goals = options_with_defaults[:goals]
self.resettable = options_with_defaults[:resettable]
self.algorithm = options_with_defaults[:algorithm]
self.metadata = options_with_defaults[:metadata]
end
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
if alts[0].is_a? Hash
alts = alts[0].map { |k, v| { k => v } }
end
end
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration
options[:metadata] = load_metadata_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
end
redis.hmset(experiment_config_key, :resettable, resettable.to_s,
:algorithm, algorithm.to_s)
self
end
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub('/', '--')
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Fix Layout/ElseAlignment
<DFF> @@ -393,7 +393,7 @@ module Split
def jstring(goal = nil)
js_id = if goal.nil?
name
- else
+ else
name + "-" + goal
end
js_id.gsub('/', '--')
| 1 | Fix Layout/ElseAlignment | 1 | .rb | rb | mit | splitrb/split |
10071361 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
expect(active_experiments.first[0]).to eq "link_color"
end
it 'should show multiple tests' do
Split.configure do |config|
config.allow_multiple_experiments = true
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #582 from splitrb/fix-active-experiments-without-finished-keys
When loading active_experiments, it should not look into user's 'finished' keys
<DFF> @@ -555,6 +555,17 @@ describe Split::Helper do
expect(active_experiments.first[0]).to eq "link_color"
end
+ it 'should show versioned tests properly' do
+ 10.times { experiment.reset }
+
+ alternative = ab_test(experiment.name, 'blue', 'red')
+ ab_finished(experiment.name, reset: false)
+
+ expect(experiment.version).to eq(10)
+ expect(active_experiments.count).to eq 1
+ expect(active_experiments).to eq({'link_color' => alternative })
+ end
+
it 'should show multiple tests' do
Split.configure do |config|
config.allow_multiple_experiments = true
| 11 | Merge pull request #582 from splitrb/fix-active-experiments-without-finished-keys | 0 | .rb | rb | mit | splitrb/split |
10071362 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
expect(active_experiments.first[0]).to eq "link_color"
end
it 'should show multiple tests' do
Split.configure do |config|
config.allow_multiple_experiments = true
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #582 from splitrb/fix-active-experiments-without-finished-keys
When loading active_experiments, it should not look into user's 'finished' keys
<DFF> @@ -555,6 +555,17 @@ describe Split::Helper do
expect(active_experiments.first[0]).to eq "link_color"
end
+ it 'should show versioned tests properly' do
+ 10.times { experiment.reset }
+
+ alternative = ab_test(experiment.name, 'blue', 'red')
+ ab_finished(experiment.name, reset: false)
+
+ expect(experiment.version).to eq(10)
+ expect(active_experiments.count).to eq 1
+ expect(active_experiments).to eq({'link_color' => alternative })
+ end
+
it 'should show multiple tests' do
Split.configure do |config|
config.allow_multiple_experiments = true
| 11 | Merge pull request #582 from splitrb/fix-active-experiments-without-finished-keys | 0 | .rb | rb | mit | splitrb/split |
10071363 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
expect(active_experiments.first[0]).to eq "link_color"
end
it 'should show multiple tests' do
Split.configure do |config|
config.allow_multiple_experiments = true
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #582 from splitrb/fix-active-experiments-without-finished-keys
When loading active_experiments, it should not look into user's 'finished' keys
<DFF> @@ -555,6 +555,17 @@ describe Split::Helper do
expect(active_experiments.first[0]).to eq "link_color"
end
+ it 'should show versioned tests properly' do
+ 10.times { experiment.reset }
+
+ alternative = ab_test(experiment.name, 'blue', 'red')
+ ab_finished(experiment.name, reset: false)
+
+ expect(experiment.version).to eq(10)
+ expect(active_experiments.count).to eq 1
+ expect(active_experiments).to eq({'link_color' => alternative })
+ end
+
it 'should show multiple tests' do
Split.configure do |config|
config.allow_multiple_experiments = true
| 11 | Merge pull request #582 from splitrb/fix-active-experiments-without-finished-keys | 0 | .rb | rb | mit | splitrb/split |
10071364 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get "/my_experiment" do
ab_test(params[:experiment], "blue", "red")
end
end
def app
@app ||= TestDashboard
end
def link(color)
Split::Alternative.new(color, experiment.name)
end
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
let(:experiment_with_goals) {
Split::ExperimentCatalog.find_or_create({ "link_color" => ["goal_1", "goal_2"] }, "blue", "red")
}
let(:metric) {
Split::Metric.find_or_create(name: "testmetric", experiments: [experiment, experiment_with_goals])
}
let(:red_link) { link("red") }
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
it "should display the start date" do
experiment_start_time = Time.parse('2011-07-07')
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment
get '/'
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
it "should handle experiments without a start date" do
experiment_start_time = Time.parse('2011-07-07')
expect(Time).to receive(:now).and_return(experiment_start_time)
Split.redis.hdel(:experiment_start_times, experiment.name)
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> Fixed bug with Time mocking in RSpec to make the tests pass.
<DFF> @@ -152,7 +152,7 @@ describe Split::Dashboard do
it "should display the start date" do
experiment_start_time = Time.parse('2011-07-07')
- expect(Time).to receive(:now).and_return(experiment_start_time)
+ expect(Time).to receive(:now).at_least(:once).and_return(experiment_start_time)
experiment
get '/'
@@ -162,7 +162,7 @@ describe Split::Dashboard do
it "should handle experiments without a start date" do
experiment_start_time = Time.parse('2011-07-07')
- expect(Time).to receive(:now).and_return(experiment_start_time)
+ expect(Time).to receive(:now).at_least(:once).and_return(experiment_start_time)
Split.redis.hdel(:experiment_start_times, experiment.name)
| 2 | Fixed bug with Time mocking in RSpec to make the tests pass. | 2 | .rb | rb | mit | splitrb/split |
10071365 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get "/my_experiment" do
ab_test(params[:experiment], "blue", "red")
end
end
def app
@app ||= TestDashboard
end
def link(color)
Split::Alternative.new(color, experiment.name)
end
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
let(:experiment_with_goals) {
Split::ExperimentCatalog.find_or_create({ "link_color" => ["goal_1", "goal_2"] }, "blue", "red")
}
let(:metric) {
Split::Metric.find_or_create(name: "testmetric", experiments: [experiment, experiment_with_goals])
}
let(:red_link) { link("red") }
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
it "should display the start date" do
experiment_start_time = Time.parse('2011-07-07')
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment
get '/'
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
it "should handle experiments without a start date" do
experiment_start_time = Time.parse('2011-07-07')
expect(Time).to receive(:now).and_return(experiment_start_time)
Split.redis.hdel(:experiment_start_times, experiment.name)
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> Fixed bug with Time mocking in RSpec to make the tests pass.
<DFF> @@ -152,7 +152,7 @@ describe Split::Dashboard do
it "should display the start date" do
experiment_start_time = Time.parse('2011-07-07')
- expect(Time).to receive(:now).and_return(experiment_start_time)
+ expect(Time).to receive(:now).at_least(:once).and_return(experiment_start_time)
experiment
get '/'
@@ -162,7 +162,7 @@ describe Split::Dashboard do
it "should handle experiments without a start date" do
experiment_start_time = Time.parse('2011-07-07')
- expect(Time).to receive(:now).and_return(experiment_start_time)
+ expect(Time).to receive(:now).at_least(:once).and_return(experiment_start_time)
Split.redis.hdel(:experiment_start_times, experiment.name)
| 2 | Fixed bug with Time mocking in RSpec to make the tests pass. | 2 | .rb | rb | mit | splitrb/split |
10071366 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get "/my_experiment" do
ab_test(params[:experiment], "blue", "red")
end
end
def app
@app ||= TestDashboard
end
def link(color)
Split::Alternative.new(color, experiment.name)
end
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
let(:experiment_with_goals) {
Split::ExperimentCatalog.find_or_create({ "link_color" => ["goal_1", "goal_2"] }, "blue", "red")
}
let(:metric) {
Split::Metric.find_or_create(name: "testmetric", experiments: [experiment, experiment_with_goals])
}
let(:red_link) { link("red") }
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
it "should display the start date" do
experiment_start_time = Time.parse('2011-07-07')
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment
get '/'
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
it "should handle experiments without a start date" do
experiment_start_time = Time.parse('2011-07-07')
expect(Time).to receive(:now).and_return(experiment_start_time)
Split.redis.hdel(:experiment_start_times, experiment.name)
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> Fixed bug with Time mocking in RSpec to make the tests pass.
<DFF> @@ -152,7 +152,7 @@ describe Split::Dashboard do
it "should display the start date" do
experiment_start_time = Time.parse('2011-07-07')
- expect(Time).to receive(:now).and_return(experiment_start_time)
+ expect(Time).to receive(:now).at_least(:once).and_return(experiment_start_time)
experiment
get '/'
@@ -162,7 +162,7 @@ describe Split::Dashboard do
it "should handle experiments without a start date" do
experiment_start_time = Time.parse('2011-07-07')
- expect(Time).to receive(:now).and_return(experiment_start_time)
+ expect(Time).to receive(:now).at_least(:once).and_return(experiment_start_time)
Split.redis.hdel(:experiment_start_times, experiment.name)
| 2 | Fixed bug with Time mocking in RSpec to make the tests pass. | 2 | .rb | rb | mit | splitrb/split |
10071367 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get '/'
last_response.should be_ok
end
end
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
end
end
end
describe "reopen experiment" do
before { experiment.winner = "red" }
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
expect(last_response).to be_redirect
end
it "removes winner" do
post "/reopen?experiment=#{experiment.name}"
expect(Split::ExperimentCatalog.find(experiment.name)).to_not have_winner
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> added dashboard reset test
<DFF> @@ -13,4 +13,26 @@ describe Split::Dashboard do
get '/'
last_response.should be_ok
end
+
+ it "should reset an experiment" do
+ experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
+ red = Split::Alternative.find('red', 'link_color').participant_count
+
+ red = Split::Alternative.find('red', 'link_color')
+ blue = Split::Alternative.find('blue', 'link_color')
+ red.participant_count = 5
+ red.save
+ blue.participant_count = 6
+ blue.save
+
+ post '/reset/link_color'
+
+ last_response.should be_redirect
+
+ new_red_count = Split::Alternative.find('red', 'link_color').participant_count
+ new_blue_count = Split::Alternative.find('blue', 'link_color').participant_count
+
+ new_blue_count.should eql(0)
+ new_red_count.should eql(0)
+ end
end
\ No newline at end of file
| 22 | added dashboard reset test | 0 | .rb | rb | mit | splitrb/split |
10071368 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get '/'
last_response.should be_ok
end
end
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
end
end
end
describe "reopen experiment" do
before { experiment.winner = "red" }
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
expect(last_response).to be_redirect
end
it "removes winner" do
post "/reopen?experiment=#{experiment.name}"
expect(Split::ExperimentCatalog.find(experiment.name)).to_not have_winner
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> added dashboard reset test
<DFF> @@ -13,4 +13,26 @@ describe Split::Dashboard do
get '/'
last_response.should be_ok
end
+
+ it "should reset an experiment" do
+ experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
+ red = Split::Alternative.find('red', 'link_color').participant_count
+
+ red = Split::Alternative.find('red', 'link_color')
+ blue = Split::Alternative.find('blue', 'link_color')
+ red.participant_count = 5
+ red.save
+ blue.participant_count = 6
+ blue.save
+
+ post '/reset/link_color'
+
+ last_response.should be_redirect
+
+ new_red_count = Split::Alternative.find('red', 'link_color').participant_count
+ new_blue_count = Split::Alternative.find('blue', 'link_color').participant_count
+
+ new_blue_count.should eql(0)
+ new_red_count.should eql(0)
+ end
end
\ No newline at end of file
| 22 | added dashboard reset test | 0 | .rb | rb | mit | splitrb/split |
10071369 | <NME> dashboard_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "rack/test"
require "split/dashboard"
describe Split::Dashboard do
include Rack::Test::Methods
class TestDashboard < Split::Dashboard
include Split::Helper
get '/'
last_response.should be_ok
end
end
let(:blue_link) { link("blue") }
before(:each) do
Split.configuration.beta_probability_simulations = 1
end
it "should respond to /" do
get "/"
expect(last_response).to be_ok
end
context "start experiment manually" do
before do
Split.configuration.start_manually = true
end
context "experiment without goals" do
it "should display a Start button" do
experiment
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
expect(last_response.body).not_to include("Metrics:")
end
end
context "experiment with metrics" do
it "should display the names of associated metrics" do
metric
get "/"
expect(last_response.body).to include("Metrics:testmetric")
end
end
context "with goals" do
it "should display a Start button" do
experiment_with_goals
get "/"
expect(last_response.body).to include("Start")
post "/start?experiment=#{experiment.name}"
get "/"
expect(last_response.body).to include("Reset Data")
end
end
end
describe "force alternative" do
context "initial version" do
let!(:user) do
Split::User.new(@app, { experiment.name => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
it "should not modify an existing user" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
expect(user[experiment.key]).to eq("red")
expect(blue_link.participant_count).to eq(7)
end
end
context "incremented version" do
let!(:user) do
experiment.increment_version
Split::User.new(@app, { "#{experiment.name}:#{experiment.version}" => "red" })
end
before do
allow(Split::User).to receive(:new).and_return(user)
end
it "should set current user's alternative" do
blue_link.participant_count = 7
post "/force_alternative?experiment=#{experiment.name}", alternative: "blue"
get "/my_experiment?experiment=#{experiment.name}"
expect(last_response.body).to include("blue")
end
end
end
describe "index page" do
context "with winner" do
before { experiment.winner = "red" }
it "displays `Reopen Experiment` button" do
get "/"
expect(last_response.body).to include("Reopen Experiment")
end
end
context "without winner" do
it "should not display `Reopen Experiment` button" do
get "/"
expect(last_response.body).to_not include("Reopen Experiment")
end
end
end
describe "reopen experiment" do
before { experiment.winner = "red" }
it "redirects" do
post "/reopen?experiment=#{experiment.name}"
expect(last_response).to be_redirect
end
it "removes winner" do
post "/reopen?experiment=#{experiment.name}"
expect(Split::ExperimentCatalog.find(experiment.name)).to_not have_winner
end
it "keeps existing stats" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reopen?experiment=#{experiment.name}"
expect(red_link.participant_count).to eq(5)
expect(blue_link.participant_count).to eq(7)
end
end
describe "update cohorting" do
it "calls enable of cohorting when action is enable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "enable" }
expect(experiment.cohorting_disabled?).to eq false
end
it "calls disable of cohorting when action is disable" do
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "disable" }
expect(experiment.cohorting_disabled?).to eq true
end
it "calls neither enable or disable cohorting when passed invalid action" do
previous_value = experiment.cohorting_disabled?
post "/update_cohorting?experiment=#{experiment.name}", { "cohorting_action": "other" }
expect(experiment.cohorting_disabled?).to eq previous_value
end
end
describe "initialize experiment" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: [ "control", "alternative" ],
}
}
end
it "initializes the experiment when the experiment is given" do
expect(Split::ExperimentCatalog.find("my_experiment")).to be nil
post "/initialize_experiment", { experiment: "my_experiment" }
experiment = Split::ExperimentCatalog.find("my_experiment")
expect(experiment).to be_a(Split::Experiment)
end
it "does not attempt to intialize the experiment when empty experiment is given" do
post "/initialize_experiment", { experiment: "" }
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
it "does not attempt to intialize the experiment when no experiment is given" do
post "/initialize_experiment"
expect(Split::ExperimentCatalog).to_not receive(:find_or_create)
end
end
it "should reset an experiment" do
red_link.participant_count = 5
blue_link.participant_count = 7
experiment.winner = "blue"
post "/reset?experiment=#{experiment.name}"
expect(last_response).to be_redirect
new_red_count = red_link.participant_count
new_blue_count = blue_link.participant_count
expect(new_blue_count).to eq(0)
expect(new_red_count).to eq(0)
expect(experiment.winner).to be_nil
end
it "should delete an experiment" do
delete "/experiment?experiment=#{experiment.name}"
expect(last_response).to be_redirect
expect(Split::ExperimentCatalog.find(experiment.name)).to be_nil
end
it "should mark an alternative as the winner" do
expect(experiment.winner).to be_nil
post "/experiment?experiment=#{experiment.name}", alternative: "red"
expect(last_response).to be_redirect
expect(experiment.winner.name).to eq("red")
end
it "should display the start date" do
experiment.start
get "/"
expect(last_response.body).to include("<small>#{experiment.start_time.strftime('%Y-%m-%d')}</small>")
end
it "should handle experiments without a start date" do
Split.redis.hdel(:experiment_start_times, experiment.name)
get "/"
expect(last_response.body).to include("<small>Unknown</small>")
end
end
<MSG> added dashboard reset test
<DFF> @@ -13,4 +13,26 @@ describe Split::Dashboard do
get '/'
last_response.should be_ok
end
+
+ it "should reset an experiment" do
+ experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
+ red = Split::Alternative.find('red', 'link_color').participant_count
+
+ red = Split::Alternative.find('red', 'link_color')
+ blue = Split::Alternative.find('blue', 'link_color')
+ red.participant_count = 5
+ red.save
+ blue.participant_count = 6
+ blue.save
+
+ post '/reset/link_color'
+
+ last_response.should be_redirect
+
+ new_red_count = Split::Alternative.find('red', 'link_color').participant_count
+ new_blue_count = Split::Alternative.find('blue', 'link_color').participant_count
+
+ new_blue_count.should eql(0)
+ new_red_count.should eql(0)
+ end
end
\ No newline at end of file
| 22 | added dashboard reset test | 0 | .rb | rb | mit | splitrb/split |
10071370 | <NME> lorem.ts
<BEF> import { ok, strictEqual as equal } from 'assert';
import expand from '../src';
function wordCount(str: string): number {
return str.split(' ').length;
}
function splitLines(str: string): string[] {
return str.split(/\n/);
}
describe('Lorem Ipsum generator', () => {
it('single', () => {
let output = expand('lorem');
ok(/^Lorem,?\sipsum/.test(output));
ok(wordCount(output) > 20);
output = expand('lorem5');
ok(/^Lorem,?\sipsum/.test(output));
equal(wordCount(output), 5);
output = expand('lorem5-10');
ok(/^Lorem,?\sipsum/.test(output));
ok(wordCount(output) >= 5 && wordCount(output) <= 10);
output = expand('p>lorem');
ok(/^<p>Lorem,?\sipsum/.test(output));
});
it('multiple', () => {
ok(/^<p><\/p>\nLorem,?\sipsum/.test(output));
});
it('multiple', () => {
let output = expand('lorem6*3');
let lines = splitLines(output);
ok(/^Lorem,?\sipsum/.test(output));
equal(lines.length, 3);
output = expand('lorem6*2');
lines = splitLines(output);
ok(/^Lorem,?\sipsum/.test(output));
equal(lines.length, 2);
output = expand('p*3>lorem');
lines = splitLines(output);
ok(/^<p>Lorem,?\sipsum/.test(lines[0]!));
ok(!/^<p>Lorem,?\sipsum/.test(lines[1]!));
output = expand('ul>lorem5*3', { options: { 'output.indent': '' } });
lines = splitLines(output);
equal(lines.length, 5);
ok(/^<li>Lorem,?\sipsum/.test(lines[1]!));
ok(!/^<li>Lorem,?\sipsum/.test(lines[2]!));
});
});
<MSG> More unit tests for Lorem ipsum generator
<DFF> @@ -25,6 +25,13 @@ describe('Lorem Ipsum generator', () => {
output = expand('p>lorem');
ok(/^<p>Lorem,?\sipsum/.test(output));
+
+ // https://github.com/emmetio/expand-abbreviation/issues/24
+ output = expand('(p)lorem2');
+ ok(/^<p><\/p>\nLorem,?\sipsum/.test(output));
+
+ output = expand('p(lorem10)');
+ ok(/^<p><\/p>\nLorem,?\sipsum/.test(output));
});
it('multiple', () => {
| 7 | More unit tests for Lorem ipsum generator | 0 | .ts | ts | mit | emmetio/emmet |
10071371 | <NME> lorem.ts
<BEF> import { ok, strictEqual as equal } from 'assert';
import expand from '../src';
function wordCount(str: string): number {
return str.split(' ').length;
}
function splitLines(str: string): string[] {
return str.split(/\n/);
}
describe('Lorem Ipsum generator', () => {
it('single', () => {
let output = expand('lorem');
ok(/^Lorem,?\sipsum/.test(output));
ok(wordCount(output) > 20);
output = expand('lorem5');
ok(/^Lorem,?\sipsum/.test(output));
equal(wordCount(output), 5);
output = expand('lorem5-10');
ok(/^Lorem,?\sipsum/.test(output));
ok(wordCount(output) >= 5 && wordCount(output) <= 10);
output = expand('p>lorem');
ok(/^<p>Lorem,?\sipsum/.test(output));
});
it('multiple', () => {
ok(/^<p><\/p>\nLorem,?\sipsum/.test(output));
});
it('multiple', () => {
let output = expand('lorem6*3');
let lines = splitLines(output);
ok(/^Lorem,?\sipsum/.test(output));
equal(lines.length, 3);
output = expand('lorem6*2');
lines = splitLines(output);
ok(/^Lorem,?\sipsum/.test(output));
equal(lines.length, 2);
output = expand('p*3>lorem');
lines = splitLines(output);
ok(/^<p>Lorem,?\sipsum/.test(lines[0]!));
ok(!/^<p>Lorem,?\sipsum/.test(lines[1]!));
output = expand('ul>lorem5*3', { options: { 'output.indent': '' } });
lines = splitLines(output);
equal(lines.length, 5);
ok(/^<li>Lorem,?\sipsum/.test(lines[1]!));
ok(!/^<li>Lorem,?\sipsum/.test(lines[2]!));
});
});
<MSG> More unit tests for Lorem ipsum generator
<DFF> @@ -25,6 +25,13 @@ describe('Lorem Ipsum generator', () => {
output = expand('p>lorem');
ok(/^<p>Lorem,?\sipsum/.test(output));
+
+ // https://github.com/emmetio/expand-abbreviation/issues/24
+ output = expand('(p)lorem2');
+ ok(/^<p><\/p>\nLorem,?\sipsum/.test(output));
+
+ output = expand('p(lorem10)');
+ ok(/^<p><\/p>\nLorem,?\sipsum/.test(output));
});
it('multiple', () => {
| 7 | More unit tests for Lorem ipsum generator | 0 | .ts | ts | mit | emmetio/emmet |
10071372 | <NME> lorem.ts
<BEF> ADDFILE
<MSG> Support Lorem Ipsum generator
<DFF> @@ -0,0 +1,47 @@
+import { ok, strictEqual as equal } from 'assert';
+import expand from '../src';
+
+function wordCount(str: string): number {
+ return str.split(' ').length;
+}
+
+function splitLines(str: string): string[] {
+ return str.split(/\n/);
+}
+
+describe('Lorem Ipsum generator', () => {
+ it('single', () => {
+ let output = expand('lorem');
+ ok(/^Lorem,?\sipsum/.test(output));
+ ok(wordCount(output) > 20);
+
+ output = expand('lorem5');
+ ok(/^Lorem,?\sipsum/.test(output));
+ equal(wordCount(output), 5);
+
+ output = expand('loremru4');
+ ok(/^Далеко-далеко,?\sза,?\sсловесными/.test(output));
+ equal(wordCount(output), 4);
+
+ output = expand('p>lorem');
+ ok(/^<p>Lorem,?\sipsum/.test(output));
+ });
+
+ it('multiple', () => {
+ let output = expand('lorem6*3');
+ let lines = splitLines(output);
+ ok(/^Lorem,?\sipsum/.test(output));
+ equal(lines.length, 3);
+
+ output = expand('p*3>lorem');
+ lines = splitLines(output);
+ ok(/^<p>Lorem,?\sipsum/.test(lines[0]!));
+ ok(!/^<p>Lorem,?\sipsum/.test(lines[1]!));
+
+ output = expand('ul>lorem5*3', { options: { 'output.indent': '' } });
+ lines = splitLines(output);
+ equal(lines.length, 5);
+ ok(/^<li>Lorem,?\sipsum/.test(lines[1]!));
+ ok(!/^<li>Lorem,?\sipsum/.test(lines[2]!));
+ });
+});
| 47 | Support Lorem Ipsum generator | 0 | .ts | ts | mit | emmetio/emmet |
10071373 | <NME> lorem.ts
<BEF> ADDFILE
<MSG> Support Lorem Ipsum generator
<DFF> @@ -0,0 +1,47 @@
+import { ok, strictEqual as equal } from 'assert';
+import expand from '../src';
+
+function wordCount(str: string): number {
+ return str.split(' ').length;
+}
+
+function splitLines(str: string): string[] {
+ return str.split(/\n/);
+}
+
+describe('Lorem Ipsum generator', () => {
+ it('single', () => {
+ let output = expand('lorem');
+ ok(/^Lorem,?\sipsum/.test(output));
+ ok(wordCount(output) > 20);
+
+ output = expand('lorem5');
+ ok(/^Lorem,?\sipsum/.test(output));
+ equal(wordCount(output), 5);
+
+ output = expand('loremru4');
+ ok(/^Далеко-далеко,?\sза,?\sсловесными/.test(output));
+ equal(wordCount(output), 4);
+
+ output = expand('p>lorem');
+ ok(/^<p>Lorem,?\sipsum/.test(output));
+ });
+
+ it('multiple', () => {
+ let output = expand('lorem6*3');
+ let lines = splitLines(output);
+ ok(/^Lorem,?\sipsum/.test(output));
+ equal(lines.length, 3);
+
+ output = expand('p*3>lorem');
+ lines = splitLines(output);
+ ok(/^<p>Lorem,?\sipsum/.test(lines[0]!));
+ ok(!/^<p>Lorem,?\sipsum/.test(lines[1]!));
+
+ output = expand('ul>lorem5*3', { options: { 'output.indent': '' } });
+ lines = splitLines(output);
+ equal(lines.length, 5);
+ ok(/^<li>Lorem,?\sipsum/.test(lines[1]!));
+ ok(!/^<li>Lorem,?\sipsum/.test(lines[2]!));
+ });
+});
| 47 | Support Lorem Ipsum generator | 0 | .ts | ts | mit | emmetio/emmet |
10071374 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.files = `git ls-files`.split("\n")
s.add_development_dependency 'rack-test', '~> 0.6'
s.add_development_dependency 'rake', '~> 11.1'
s.add_development_dependency 'rspec', '~> 3.4'
end
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Add pry gem
This is helpful for debugging.
<DFF> @@ -30,4 +30,5 @@ Gem::Specification.new do |s|
s.add_development_dependency 'rack-test', '~> 0.6'
s.add_development_dependency 'rake', '~> 11.1'
s.add_development_dependency 'rspec', '~> 3.4'
+ s.add_development_dependency 'pry'
end
| 1 | Add pry gem | 0 | .gemspec | gemspec | mit | splitrb/split |
10071375 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.files = `git ls-files`.split("\n")
s.add_development_dependency 'rack-test', '~> 0.6'
s.add_development_dependency 'rake', '~> 11.1'
s.add_development_dependency 'rspec', '~> 3.4'
end
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Add pry gem
This is helpful for debugging.
<DFF> @@ -30,4 +30,5 @@ Gem::Specification.new do |s|
s.add_development_dependency 'rack-test', '~> 0.6'
s.add_development_dependency 'rake', '~> 11.1'
s.add_development_dependency 'rspec', '~> 3.4'
+ s.add_development_dependency 'pry'
end
| 1 | Add pry gem | 0 | .gemspec | gemspec | mit | splitrb/split |
10071376 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
s.files = `git ls-files`.split("\n")
s.add_development_dependency 'rack-test', '~> 0.6'
s.add_development_dependency 'rake', '~> 11.1'
s.add_development_dependency 'rspec', '~> 3.4'
end
s.add_dependency "rubystats", ">= 0.3.0"
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Add pry gem
This is helpful for debugging.
<DFF> @@ -30,4 +30,5 @@ Gem::Specification.new do |s|
s.add_development_dependency 'rack-test', '~> 0.6'
s.add_development_dependency 'rake', '~> 11.1'
s.add_development_dependency 'rspec', '~> 3.4'
+ s.add_development_dependency 'pry'
end
| 1 | Add pry gem | 0 | .gemspec | gemspec | mit | splitrb/split |
10071377 | <NME> README.md
<BEF> # [Split](https://libraries.io/rubygems/split)
[](http://badge.fury.io/rb/split)

[](https://codeclimate.com/github/splitrb/split)
[](https://codeclimate.com/github/splitrb/split/coverage)
[](https://github.com/RichardLitt/standard-readme)
[](https://www.codetriage.com/splitrb/split)
> 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split
Split is a rack based A/B testing framework designed to work with Rails, Sinatra or any other rack based app.
Split is heavily inspired by the [Abingo](https://github.com/ryanb/abingo) and [Vanity](https://github.com/assaf/vanity) Rails A/B testing plugins and [Resque](https://github.com/resque/resque) in its use of Redis.
Split is designed to be hacker friendly, allowing for maximum customisation and extensibility.
## Install
### Requirements
Split v4.0+ is currently tested with Ruby >= 2.5 and Rails >= 5.2.
If your project requires compatibility with Ruby 2.4.x or older Rails versions. You can try v3.0 or v0.8.0(for Ruby 1.9.3)
Split uses Redis as a datastore.
Split only supports Redis 4.0 or greater.
If you're on OS X, Homebrew is the simplest way to install Redis:
```bash
brew install redis
redis-server /usr/local/etc/redis.conf
```
You now have a Redis daemon running on port `6379`.
### Setup
```bash
gem install split
```
#### Rails
Adding `gem 'split'` to your Gemfile will autoload it when rails starts up, as long as you've configured Redis it will 'just work'.
#### Sinatra
To configure Sinatra with Split you need to enable sessions and mix in the helper methods. Add the following lines at the top of your Sinatra app:
```ruby
require 'split'
class MySinatraApp < Sinatra::Base
enable :sessions
helpers Split::Helper
get '/' do
...
end
```
## Usage
To begin your A/B test use the `ab_test` method, naming your experiment with the first argument and then the different alternatives which you wish to test on as the other arguments.
`ab_test` returns one of the alternatives, if a user has already seen that test they will get the same alternative as before, which you can use to split your code on.
It can be used to render different templates, show different text or any other case based logic.
`ab_finished` is used to make a completion of an experiment, or conversion.
Example: View
```erb
<% ab_test(:login_button, "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
<%= image_tag(button_file, alt: "Login!") %>
<% end %>
```
Example: Controller
```ruby
def register_new_user
# See what level of free points maximizes users' decision to buy replacement points.
@starter_points = ab_test(:new_user_free_points, '100', '200', '300')
end
```
Example: Conversion tracking (in a controller!)
```ruby
def buy_new_points
# some business logic
ab_finished(:new_user_free_points)
end
```
Example: Conversion tracking (in a view)
```erb
Thanks for signing up, dude! <% ab_finished(:signup_page_redesign) %>
```
You can find more examples, tutorials and guides on the [wiki](https://github.com/splitrb/split/wiki).
## Statistical Validity
Split has two options for you to use to determine which alternative is the best.
The first option (default on the dashboard) uses a z test (n>30) for the difference between your control and alternative conversion rates to calculate statistical significance. This test will tell you whether an alternative is better or worse than your control, but it will not distinguish between which alternative is the best in an experiment with multiple alternatives. Split will only tell you if your experiment is 90%, 95%, or 99% significant, and this test only works if you have more than 30 participants and 5 conversions for each branch.
As per this [blog post](https://www.evanmiller.org/how-not-to-run-an-ab-test.html) on the pitfalls of A/B testing, it is highly recommended that you determine your requisite sample size for each branch before running the experiment. Otherwise, you'll have an increased rate of false positives (experiments which show a significant effect where really there is none).
[Here](https://www.evanmiller.org/ab-testing/sample-size.html) is a sample size calculator for your convenience.
The second option uses simulations from a beta distribution to determine the probability that the given alternative is the winner compared to all other alternatives. You can view these probabilities by clicking on the drop-down menu labeled "Confidence." This option should be used when the experiment has more than just 1 control and 1 alternative. It can also be used for a simple, 2-alternative A/B test.
Calculating the beta-distribution simulations for a large number of experiments can be slow, so the results are cached. You can specify how often they should be recalculated (the default is once per day).
```ruby
Split.configure do |config|
config.winning_alternative_recalculation_interval = 3600 # 1 hour
end
```
## Extras
### Weighted alternatives
Perhaps you only want to show an alternative to 10% of your visitors because it is very experimental or not yet fully load tested.
To do this you can pass a weight with each alternative in the following ways:
```ruby
ab_test(:homepage_design, {'Old' => 18}, {'New' => 2})
ab_test(:homepage_design, 'Old', {'New' => 1.0/9})
ab_test(:homepage_design, {'Old' => 9}, 'New')
```
This will only show the new alternative to visitors 1 in 10 times, the default weight for an alternative is 1.
### Overriding alternatives
For development and testing, you may wish to force your app to always return an alternative.
You can do this by passing it as a parameter in the url.
If you have an experiment called `button_color` with alternatives called `red` and `blue` used on your homepage, a url such as:
http://myawesomesite.com?ab_test[button_color]=red
will always have red buttons. This won't be stored in your session or count towards to results, unless you set the `store_override` configuration option.
In the event you want to disable all tests without having to know the individual experiment names, add a `SPLIT_DISABLE` query parameter.
http://myawesomesite.com?SPLIT_DISABLE=true
It is not required to send `SPLIT_DISABLE=false` to activate Split.
### Rspec Helper
To aid testing with RSpec, write `spec/support/split_helper.rb` and call `use_ab_test(alternatives_by_experiment)` in your specs as instructed below:
```ruby
# Create a file with these contents at 'spec/support/split_helper.rb'
# and ensure it is `require`d in your rails_helper.rb or spec_helper.rb
module SplitHelper
# Force a specific experiment alternative to always be returned:
# use_ab_test(signup_form: "single_page")
#
# Force alternatives for multiple experiments:
# use_ab_test(signup_form: "single_page", pricing: "show_enterprise_prices")
#
def use_ab_test(alternatives_by_experiment)
allow_any_instance_of(Split::Helper).to receive(:ab_test) do |_receiver, experiment, &block|
variant = alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" }
block.call(variant) unless block.nil?
variant
end
end
end
# Make the `use_ab_test` method available to all specs:
RSpec.configure do |config|
config.include SplitHelper
end
```
Now you can call `use_ab_test(alternatives_by_experiment)` in your specs, for example:
```ruby
it "registers using experimental signup" do
use_ab_test experiment_name: "alternative_name"
post "/signups"
...
end
```
### Starting experiments manually
By default new A/B tests will be active right after deployment. In case you would like to start new test a while after
the deploy, you can do it by setting the `start_manually` configuration option to `true`.
After choosing this option tests won't be started right after deploy, but after pressing the `Start` button in Split admin dashboard. If a test is deleted from the Split dashboard, then it can only be started after pressing the `Start` button whenever being re-initialized.
### Reset after completion
When a user completes a test their session is reset so that they may start the test again in the future.
To stop this behaviour you can pass the following option to the `ab_finished` method:
```ruby
ab_finished(:experiment_name, reset: false)
```
The user will then always see the alternative they started with.
Any old unfinished experiment key will be deleted from the user's data storage if the experiment had been removed or is over and a winner had been chosen. This allows a user to enroll into any new experiment in cases when the `allow_multiple_experiments` config option is set to `false`.
### Reset experiments manually
By default Split automatically resets the experiment whenever it detects the configuration for an experiment has changed (e.g. you call `ab_test` with different alternatives). You can prevent this by setting the option `reset_manually` to `true`.
You may want to do this when you want to change something, like the variants' names, the metadata about an experiment, etc. without resetting everything.
### Multiple experiments at once
By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests.
To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = true
end
```
This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another.
To address this, setting the `allow_multiple_experiments` config option to 'control' like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = 'control'
end
```
For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment.
### Experiment Persistence
Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment.
By default Split will store the tests for each user in the session.
You can optionally configure Split to use a cookie, Redis, or any custom adapter of your choosing.
#### Cookies
```ruby
Split.configure do |config|
config.persistence = :cookie
end
```
When using the cookie persistence, Split stores data into an anonymous tracking cookie named 'split', which expires in 1 year. To change that, set the `persistence_cookie_length` in the configuration (unit of time in seconds).
```ruby
Split.configure do |config|
config.persistence = :cookie
config.persistence_cookie_length = 2592000 # 30 days
end
```
The data stored consists of the experiment name and the variants the user is in. Example: { "experiment_name" => "variant_a" }
__Note:__ Using cookies depends on `ActionDispatch::Cookies` or any identical API
#### Redis
Using Redis will allow ab_users to persist across sessions or machines.
```ruby
Split.configure do |config|
config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: -> (context) { context.current_user_id })
# Equivalent
# config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: :current_user_id)
end
```
Options:
* `lookup_by`: method to invoke per request for uniquely identifying ab_users (mandatory configuration)
* `namespace`: separate namespace to store these persisted values (default "persistence")
* `expire_seconds`: sets TTL for user key. (if a user is in multiple experiments most recent update will reset TTL for all their assignments)
#### Dual Adapter
The Dual Adapter allows the use of different persistence adapters for logged-in and logged-out users. A common use case is to use Redis for logged-in users and Cookies for logged-out users.
```ruby
cookie_adapter = Split::Persistence::CookieAdapter
redis_adapter = Split::Persistence::RedisAdapter.with_config(
lookup_by: -> (context) { context.send(:current_user).try(:id) },
expire_seconds: 2592000)
Split.configure do |config|
config.persistence = Split::Persistence::DualAdapter.with_config(
logged_in: -> (context) { !context.send(:current_user).try(:id).nil? },
logged_in_adapter: redis_adapter,
logged_out_adapter: cookie_adapter)
config.persistence_cookie_length = 2592000 # 30 days
end
```
#### Custom Adapter
Your custom adapter needs to implement the same API as existing adapters.
See `Split::Persistence::CookieAdapter` or `Split::Persistence::SessionAdapter` for a starting point.
```ruby
Split.configure do |config|
config.persistence = YourCustomAdapterClass
end
```
### Trial Event Hooks
You can define methods that will be called at the same time as experiment
alternative participation and goal completion.
For example:
``` ruby
Split.configure do |config|
config.on_trial = :log_trial # run on every trial
config.on_trial_choose = :log_trial_choose # run on trials with new users only
config.on_trial_complete = :log_trial_complete
end
```
Set these attributes to a method name available in the same context as the
`ab_test` method. These methods should accept one argument, a `Trial` instance.
``` ruby
def log_trial(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_choose(trial)
logger.info "[new user] experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_complete(trial)
logger.info "experiment=%s alternative=%s user=%s complete=true" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
#### Views
If you are running `ab_test` from a view, you must define your event
hook callback as a
[helper_method](https://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method)
in the controller:
``` ruby
helper_method :log_trial_choose
def log_trial_choose(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
### Experiment Hooks
You can assign a proc that will be called when an experiment is reset or deleted. You can use these hooks to call methods within your application to keep data related to experiments in sync with Split.
For example:
``` ruby
Split.configure do |config|
# after experiment reset or deleted
config.on_experiment_reset = -> (example) { # Do something on reset }
config.on_experiment_delete = -> (experiment) { # Do something else on delete }
# before experiment reset or deleted
config.on_before_experiment_reset = -> (example) { # Do something on reset }
config.on_before_experiment_delete = -> (experiment) { # Do something else on delete }
# after experiment winner had been set
config.on_experiment_winner_choose = -> (experiment) { # Do something on winner choose }
end
```
## Web Interface
Split comes with a Sinatra-based front end to get an overview of how your experiments are doing.
If you are running Rails 2: You can mount this inside your app using Rack::URLMap in your `config.ru`
```ruby
require 'split/dashboard'
run Rack::URLMap.new \
"/" => Your::App.new,
"/split" => Split::Dashboard.new
```
However, if you are using Rails 3 or higher: You can mount this inside your app routes by first adding this to the Gemfile:
```ruby
gem 'split', require: 'split/dashboard'
```
Then adding this to config/routes.rb
```ruby
mount Split::Dashboard, at: 'split'
```
You may want to password protect that page, you can do so with `Rack::Auth::Basic` (in your split initializer file)
```ruby
# Rails apps or apps that already depend on activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
alternatives:
- a
- b
meta:
a:
text: "Have a fantastic day"
b:
text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
```
You can even use Devise or any other Warden-based authentication method to authorize users. Just replace `mount Split::Dashboard, :at => 'split'` in `config/routes.rb` with the following:
```ruby
match "/split" => Split::Dashboard, anchor: false, via: [:get, :post, :delete], constraints: -> (request) do
request.env['warden'].authenticated? # are we authenticated?
request.env['warden'].authenticate! # authenticate if not already
# or even check any other condition such as request.env['warden'].user.is_admin?
end
```
More information on this [here](https://steve.dynedge.co.uk/2011/12/09/controlling-access-to-routes-and-rack-apps-in-rails-3-with-devise-and-warden/)
### Screenshot

## Configuration
You can override the default configuration options of Split like so:
```ruby
Split.configure do |config|
config.db_failover = true # handle Redis errors gracefully
config.db_failover_on_db_error = -> (error) { Rails.logger.error(error.message) }
config.allow_multiple_experiments = true
config.enabled = true
config.persistence = Split::Persistence::SessionAdapter
#config.start_manually = false ## new test will have to be started manually from the admin panel. default false
#config.reset_manually = false ## if true, it never resets the experiment data, even if the configuration changes
config.include_rails_helper = true
config.redis = "redis://custom.redis.url:6380"
end
```
Split looks for the Redis host in the environment variable `REDIS_URL` then
defaults to `redis://localhost:6379` if not specified by configure block.
On platforms like Heroku, Split will use the value of `REDIS_PROVIDER` to
determine which env variable key to use when retrieving the host config. This
defaults to `REDIS_URL`.
### Filtering
In most scenarios you don't want to have AB-Testing enabled for web spiders, robots or special groups of users.
Split provides functionality to filter this based on a predefined, extensible list of bots, IP-lists or custom exclude logic.
```ruby
Split.configure do |config|
# bot config
config.robot_regex = /my_custom_robot_regex/ # or
config.bots['newbot'] = "Description for bot with 'newbot' user agent, which will be added to config.robot_regex for exclusion"
# IP config
config.ignore_ip_addresses << '81.19.48.130' # or regex: /81\.19\.48\.[0-9]+/
# or provide your own filter functionality, the default is proc{ |request| is_robot? || is_ignored_ip_address? || is_preview? }
config.ignore_filter = -> (request) { CustomExcludeLogic.excludes?(request) }
end
```
### Experiment configuration
Instead of providing the experiment options inline, you can store them
in a hash. This hash can control your experiment's alternatives, weights,
algorithm and if the experiment resets once finished:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
resettable: false
},
:my_second_experiment => {
algorithm: 'Split::Algorithms::Whiplash',
alternatives: [
{ name: "a", percent: 67 },
{ name: "b", percent: 33 }
]
}
}
end
```
You can also store your experiments in a YAML file:
```ruby
Split.configure do |config|
config.experiments = YAML.load_file "config/experiments.yml"
end
```
You can then define the YAML file like:
```yaml
my_first_experiment:
alternatives:
- a
- b
my_second_experiment:
alternatives:
- name: a
percent: 67
- name: b
percent: 33
resettable: false
```
This simplifies the calls from your code:
```ruby
ab_test(:my_first_experiment)
```
and:
```ruby
ab_finished(:my_first_experiment)
```
You can also add meta data for each experiment, which is very useful when you need more than an alternative name to change behaviour:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metadata: {
"a" => {"text" => "Have a fantastic day"},
"b" => {"text" => "Don't get hit by a bus"}
}
}
}
end
```
```yaml
my_first_experiment:
alternatives:
- a
- b
metadata:
a:
text: "Have a fantastic day"
b:
text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
```ruby
trial.alternative.name # => "a"
trial.metadata['text'] # => "Have a fantastic day"
```
or in views:
```erb
<% ab_test("my_first_experiment") do |alternative, meta| %>
<%= alternative %>
<small><%= meta['text'] %></small>
<% end %>
```
The keys used in meta data should be Strings
#### Metrics
You might wish to track generic metrics, such as conversions, and use
those to complete multiple different experiments without adding more to
your code. You can use the configuration hash to do this, thanks to
the `:metric` option.
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metric: :my_metric
}
}
end
```
Your code may then track a completion using the metric instead of
the experiment name:
```ruby
ab_finished(:my_metric)
```
You can also create a new metric by instantiating and saving a new Metric object.
```ruby
Split::Metric.new(:my_metric)
Split::Metric.save
```
#### Goals
You might wish to allow an experiment to have multiple, distinguishable goals.
The API to define goals for an experiment is this:
```ruby
ab_test({link_color: ["purchase", "refund"]}, "red", "blue")
```
or you can define them in a configuration file:
```ruby
Split.configure do |config|
config.experiments = {
link_color: {
alternatives: ["red", "blue"],
goals: ["purchase", "refund"]
}
}
end
```
To complete a goal conversion, you do it like:
```ruby
ab_finished(link_color: "purchase")
```
Note that if you pass additional options, that should be a separate hash:
```ruby
ab_finished({ link_color: "purchase" }, reset: false)
```
**NOTE:** This does not mean that a single experiment can complete more than one goal.
Once you finish one of the goals, the test is considered to be completed, and finishing the other goal will no longer register. (Assuming the test runs with `reset: false`.)
**Good Example**: Test if listing Plan A first result in more conversions to Plan A (goal: "plana_conversion") or Plan B (goal: "planb_conversion").
**Bad Example**: Test if button color increases conversion rate through multiple steps of a funnel. THIS WILL NOT WORK.
**Bad Example**: Test both how button color affects signup *and* how it affects login, at the same time. THIS WILL NOT WORK.
#### Combined Experiments
If you want to test how button color affects signup *and* how it affects login at the same time, use combined experiments.
Configure like so:
```ruby
Split.configuration.experiments = {
:button_color_experiment => {
:alternatives => ["blue", "green"],
:combined_experiments => ["button_color_on_signup", "button_color_on_login"]
}
}
```
Starting the combined test starts all combined experiments
```ruby
ab_combined_test(:button_color_experiment)
```
Finish each combined test as normal
```ruby
ab_finished(:button_color_on_login)
ab_finished(:button_color_on_signup)
```
**Additional Configuration**:
* Be sure to enable `allow_multiple_experiments`
* In Sinatra include the CombinedExperimentsHelper
```
helpers Split::CombinedExperimentsHelper
```
### DB failover solution
Due to the fact that Redis has no automatic failover mechanism, it's
possible to switch on the `db_failover` config option, so that `ab_test`
and `ab_finished` will not crash in case of a db failure. `ab_test` always
delivers alternative A (the first one) in that case.
It's also possible to set a `db_failover_on_db_error` callback (proc)
for example to log these errors via Rails.logger.
### Redis
You may want to change the Redis host and port Split connects to, or
set various other options at startup.
Split has a `redis` setter which can be given a string or a Redis
object. This means if you're already using Redis in your app, Split
can re-use the existing connection.
String: `Split.redis = 'redis://localhost:6379'`
Redis: `Split.redis = $redis`
For our rails app we have a `config/initializers/split.rb` file where
we load `config/split.yml` by hand and set the Redis information
appropriately.
Here's our `config/split.yml`:
```yml
development: redis://localhost:6379
test: redis://localhost:6379
staging: redis://redis1.example.com:6379
fi: redis://localhost:6379
production: redis://redis1.example.com:6379
```
And our initializer:
```ruby
split_config = YAML.load_file(Rails.root.join('config', 'split.yml'))
Split.redis = split_config[Rails.env]
```
### Redis Caching (v4.0+)
In some high-volume usage scenarios, Redis load can be incurred by repeated
fetches for fairly static data. Enabling caching will reduce this load.
```ruby
Split.configuration.cache = true
````
This currently caches:
- `Split::ExperimentCatalog.find`
- `Split::Experiment.start_time`
- `Split::Experiment.winner`
## Namespaces
If you're running multiple, separate instances of Split you may want
to namespace the keyspaces so they do not overlap. This is not unlike
the approach taken by many memcached clients.
This feature can be provided by the [redis-namespace](https://github.com/defunkt/redis-namespace)
library. To configure Split to use `Redis::Namespace`, do the following:
1. Add `redis-namespace` to your Gemfile:
```ruby
gem 'redis-namespace'
```
2. Configure `Split.redis` to use a `Redis::Namespace` instance (possible in an
initializer):
```ruby
redis = Redis.new(url: ENV['REDIS_URL']) # or whatever config you want
Split.redis = Redis::Namespace.new(:your_namespace, redis: redis)
```
## Outside of a Web Session
Split provides the Helper module to facilitate running experiments inside web sessions.
Alternatively, you can access the underlying Metric, Trial, Experiment and Alternative objects to
conduct experiments that are not tied to a web session.
```ruby
# create a new experiment
experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue')
# create a new trial
trial = Split::Trial.new(:experiment => experiment)
# run trial
trial.choose!
# get the result, returns either red or blue
trial.alternative.name
# if the goal has been achieved, increment the successful completions for this alternative.
if goal_achieved?
trial.complete!
end
```
## Algorithms
By default, Split ships with `Split::Algorithms::WeightedSample` that randomly selects from possible alternatives for a traditional a/b test.
It is possible to specify static weights to favor certain alternatives.
`Split::Algorithms::Whiplash` is an implementation of a [multi-armed bandit algorithm](http://stevehanov.ca/blog/index.php?id=132).
This algorithm will automatically weight the alternatives based on their relative performance,
choosing the better-performing ones more often as trials are completed.
`Split::Algorithms::BlockRandomization` is an algorithm that ensures equal
participation across all alternatives. This algorithm will choose the alternative
with the fewest participants. In the event of multiple minimum participant alternatives
(i.e. starting a new "Block") the algorithm will choose a random alternative from
those minimum participant alternatives.
Users may also write their own algorithms. The default algorithm may be specified globally in the configuration file, or on a per experiment basis using the experiments hash of the configuration file.
To change the algorithm globally for all experiments, use the following in your initializer:
```ruby
Split.configure do |config|
config.algorithm = Split::Algorithms::Whiplash
end
```
## Extensions
- [Split::Export](https://github.com/splitrb/split-export) - Easily export A/B test data out of Split.
- [Split::Analytics](https://github.com/splitrb/split-analytics) - Push test data to Google Analytics.
- [Split::Mongoid](https://github.com/MongoHQ/split-mongoid) - Store experiment data in mongoid (still uses redis).
- [Split::Cacheable](https://github.com/harrystech/split_cacheable) - Automatically create cache buckets per test.
- [Split::Counters](https://github.com/bernardkroes/split-counters) - Add counters per experiment and alternative.
- [Split::Cli](https://github.com/craigmcnamara/split-cli) - A CLI to trigger Split A/B tests.
## Screencast
Ryan bates has produced an excellent 10 minute screencast about split on the Railscasts site: [A/B Testing with Split](http://railscasts.com/episodes/331-a-b-testing-with-split)
## Blogposts
* [Recipe: A/B testing with KISSMetrics and the split gem](https://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem)
* [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html)
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/split#backer)]
<a href="https://opencollective.com/split/backer/0/website" target="_blank"><img src="https://opencollective.com/split/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/1/website" target="_blank"><img src="https://opencollective.com/split/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/2/website" target="_blank"><img src="https://opencollective.com/split/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/3/website" target="_blank"><img src="https://opencollective.com/split/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/4/website" target="_blank"><img src="https://opencollective.com/split/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/5/website" target="_blank"><img src="https://opencollective.com/split/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/6/website" target="_blank"><img src="https://opencollective.com/split/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/7/website" target="_blank"><img src="https://opencollective.com/split/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/8/website" target="_blank"><img src="https://opencollective.com/split/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/9/website" target="_blank"><img src="https://opencollective.com/split/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/10/website" target="_blank"><img src="https://opencollective.com/split/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/11/website" target="_blank"><img src="https://opencollective.com/split/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/12/website" target="_blank"><img src="https://opencollective.com/split/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/13/website" target="_blank"><img src="https://opencollective.com/split/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/14/website" target="_blank"><img src="https://opencollective.com/split/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/15/website" target="_blank"><img src="https://opencollective.com/split/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/16/website" target="_blank"><img src="https://opencollective.com/split/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/17/website" target="_blank"><img src="https://opencollective.com/split/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/18/website" target="_blank"><img src="https://opencollective.com/split/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/19/website" target="_blank"><img src="https://opencollective.com/split/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/20/website" target="_blank"><img src="https://opencollective.com/split/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/21/website" target="_blank"><img src="https://opencollective.com/split/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/22/website" target="_blank"><img src="https://opencollective.com/split/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/23/website" target="_blank"><img src="https://opencollective.com/split/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/24/website" target="_blank"><img src="https://opencollective.com/split/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/25/website" target="_blank"><img src="https://opencollective.com/split/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/26/website" target="_blank"><img src="https://opencollective.com/split/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/27/website" target="_blank"><img src="https://opencollective.com/split/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/28/website" target="_blank"><img src="https://opencollective.com/split/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/29/website" target="_blank"><img src="https://opencollective.com/split/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/split#sponsor)]
<a href="https://opencollective.com/split/sponsor/0/website" target="_blank"><img src="https://opencollective.com/split/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/1/website" target="_blank"><img src="https://opencollective.com/split/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/2/website" target="_blank"><img src="https://opencollective.com/split/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/3/website" target="_blank"><img src="https://opencollective.com/split/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/4/website" target="_blank"><img src="https://opencollective.com/split/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/5/website" target="_blank"><img src="https://opencollective.com/split/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/6/website" target="_blank"><img src="https://opencollective.com/split/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/7/website" target="_blank"><img src="https://opencollective.com/split/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/8/website" target="_blank"><img src="https://opencollective.com/split/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/9/website" target="_blank"><img src="https://opencollective.com/split/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/10/website" target="_blank"><img src="https://opencollective.com/split/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/11/website" target="_blank"><img src="https://opencollective.com/split/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/12/website" target="_blank"><img src="https://opencollective.com/split/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/13/website" target="_blank"><img src="https://opencollective.com/split/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/14/website" target="_blank"><img src="https://opencollective.com/split/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/15/website" target="_blank"><img src="https://opencollective.com/split/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/16/website" target="_blank"><img src="https://opencollective.com/split/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/17/website" target="_blank"><img src="https://opencollective.com/split/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/18/website" target="_blank"><img src="https://opencollective.com/split/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/19/website" target="_blank"><img src="https://opencollective.com/split/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/20/website" target="_blank"><img src="https://opencollective.com/split/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/21/website" target="_blank"><img src="https://opencollective.com/split/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/22/website" target="_blank"><img src="https://opencollective.com/split/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/23/website" target="_blank"><img src="https://opencollective.com/split/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/24/website" target="_blank"><img src="https://opencollective.com/split/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/25/website" target="_blank"><img src="https://opencollective.com/split/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/26/website" target="_blank"><img src="https://opencollective.com/split/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/27/website" target="_blank"><img src="https://opencollective.com/split/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/28/website" target="_blank"><img src="https://opencollective.com/split/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/29/website" target="_blank"><img src="https://opencollective.com/split/sponsor/29/avatar.svg"></a>
## Contribute
Please do! Over 70 different people have contributed to the project, you can see them all here: https://github.com/splitrb/split/graphs/contributors.
### Development
The source code is hosted at [GitHub](https://github.com/splitrb/split).
Report issues and feature requests on [GitHub Issues](https://github.com/splitrb/split/issues).
You can find a discussion form on [Google Groups](https://groups.google.com/d/forum/split-ruby).
### Tests
Run the tests like this:
# Start a Redis server in another tab.
redis-server
bundle
rake spec
### A Note on Patches and Pull Requests
* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
future version unintentionally.
* Add documentation if necessary.
* Commit. Do not mess with the rakefile, version, or history.
(If you want to have your own version, that is fine. But bump the version in a commit by itself, which I can ignore when I pull.)
* Send a pull request. Bonus points for topic branches.
### Code of Conduct
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
## Copyright
[MIT License](LICENSE) © 2019 [Andrew Nesbitt](https://github.com/andrew).
<MSG> Fixes experiment metadata doc
<DFF> @@ -435,11 +435,11 @@ my_first_experiment:
alternatives:
- a
- b
- meta:
- a:
- text: "Have a fantastic day"
- b:
- text: "Don't get hit by a bus"
+ metadata:
+ a:
+ text: "Have a fantastic day"
+ b:
+ text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
| 5 | Fixes experiment metadata doc | 5 | .md | md | mit | splitrb/split |
10071378 | <NME> README.md
<BEF> # [Split](https://libraries.io/rubygems/split)
[](http://badge.fury.io/rb/split)

[](https://codeclimate.com/github/splitrb/split)
[](https://codeclimate.com/github/splitrb/split/coverage)
[](https://github.com/RichardLitt/standard-readme)
[](https://www.codetriage.com/splitrb/split)
> 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split
Split is a rack based A/B testing framework designed to work with Rails, Sinatra or any other rack based app.
Split is heavily inspired by the [Abingo](https://github.com/ryanb/abingo) and [Vanity](https://github.com/assaf/vanity) Rails A/B testing plugins and [Resque](https://github.com/resque/resque) in its use of Redis.
Split is designed to be hacker friendly, allowing for maximum customisation and extensibility.
## Install
### Requirements
Split v4.0+ is currently tested with Ruby >= 2.5 and Rails >= 5.2.
If your project requires compatibility with Ruby 2.4.x or older Rails versions. You can try v3.0 or v0.8.0(for Ruby 1.9.3)
Split uses Redis as a datastore.
Split only supports Redis 4.0 or greater.
If you're on OS X, Homebrew is the simplest way to install Redis:
```bash
brew install redis
redis-server /usr/local/etc/redis.conf
```
You now have a Redis daemon running on port `6379`.
### Setup
```bash
gem install split
```
#### Rails
Adding `gem 'split'` to your Gemfile will autoload it when rails starts up, as long as you've configured Redis it will 'just work'.
#### Sinatra
To configure Sinatra with Split you need to enable sessions and mix in the helper methods. Add the following lines at the top of your Sinatra app:
```ruby
require 'split'
class MySinatraApp < Sinatra::Base
enable :sessions
helpers Split::Helper
get '/' do
...
end
```
## Usage
To begin your A/B test use the `ab_test` method, naming your experiment with the first argument and then the different alternatives which you wish to test on as the other arguments.
`ab_test` returns one of the alternatives, if a user has already seen that test they will get the same alternative as before, which you can use to split your code on.
It can be used to render different templates, show different text or any other case based logic.
`ab_finished` is used to make a completion of an experiment, or conversion.
Example: View
```erb
<% ab_test(:login_button, "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
<%= image_tag(button_file, alt: "Login!") %>
<% end %>
```
Example: Controller
```ruby
def register_new_user
# See what level of free points maximizes users' decision to buy replacement points.
@starter_points = ab_test(:new_user_free_points, '100', '200', '300')
end
```
Example: Conversion tracking (in a controller!)
```ruby
def buy_new_points
# some business logic
ab_finished(:new_user_free_points)
end
```
Example: Conversion tracking (in a view)
```erb
Thanks for signing up, dude! <% ab_finished(:signup_page_redesign) %>
```
You can find more examples, tutorials and guides on the [wiki](https://github.com/splitrb/split/wiki).
## Statistical Validity
Split has two options for you to use to determine which alternative is the best.
The first option (default on the dashboard) uses a z test (n>30) for the difference between your control and alternative conversion rates to calculate statistical significance. This test will tell you whether an alternative is better or worse than your control, but it will not distinguish between which alternative is the best in an experiment with multiple alternatives. Split will only tell you if your experiment is 90%, 95%, or 99% significant, and this test only works if you have more than 30 participants and 5 conversions for each branch.
As per this [blog post](https://www.evanmiller.org/how-not-to-run-an-ab-test.html) on the pitfalls of A/B testing, it is highly recommended that you determine your requisite sample size for each branch before running the experiment. Otherwise, you'll have an increased rate of false positives (experiments which show a significant effect where really there is none).
[Here](https://www.evanmiller.org/ab-testing/sample-size.html) is a sample size calculator for your convenience.
The second option uses simulations from a beta distribution to determine the probability that the given alternative is the winner compared to all other alternatives. You can view these probabilities by clicking on the drop-down menu labeled "Confidence." This option should be used when the experiment has more than just 1 control and 1 alternative. It can also be used for a simple, 2-alternative A/B test.
Calculating the beta-distribution simulations for a large number of experiments can be slow, so the results are cached. You can specify how often they should be recalculated (the default is once per day).
```ruby
Split.configure do |config|
config.winning_alternative_recalculation_interval = 3600 # 1 hour
end
```
## Extras
### Weighted alternatives
Perhaps you only want to show an alternative to 10% of your visitors because it is very experimental or not yet fully load tested.
To do this you can pass a weight with each alternative in the following ways:
```ruby
ab_test(:homepage_design, {'Old' => 18}, {'New' => 2})
ab_test(:homepage_design, 'Old', {'New' => 1.0/9})
ab_test(:homepage_design, {'Old' => 9}, 'New')
```
This will only show the new alternative to visitors 1 in 10 times, the default weight for an alternative is 1.
### Overriding alternatives
For development and testing, you may wish to force your app to always return an alternative.
You can do this by passing it as a parameter in the url.
If you have an experiment called `button_color` with alternatives called `red` and `blue` used on your homepage, a url such as:
http://myawesomesite.com?ab_test[button_color]=red
will always have red buttons. This won't be stored in your session or count towards to results, unless you set the `store_override` configuration option.
In the event you want to disable all tests without having to know the individual experiment names, add a `SPLIT_DISABLE` query parameter.
http://myawesomesite.com?SPLIT_DISABLE=true
It is not required to send `SPLIT_DISABLE=false` to activate Split.
### Rspec Helper
To aid testing with RSpec, write `spec/support/split_helper.rb` and call `use_ab_test(alternatives_by_experiment)` in your specs as instructed below:
```ruby
# Create a file with these contents at 'spec/support/split_helper.rb'
# and ensure it is `require`d in your rails_helper.rb or spec_helper.rb
module SplitHelper
# Force a specific experiment alternative to always be returned:
# use_ab_test(signup_form: "single_page")
#
# Force alternatives for multiple experiments:
# use_ab_test(signup_form: "single_page", pricing: "show_enterprise_prices")
#
def use_ab_test(alternatives_by_experiment)
allow_any_instance_of(Split::Helper).to receive(:ab_test) do |_receiver, experiment, &block|
variant = alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" }
block.call(variant) unless block.nil?
variant
end
end
end
# Make the `use_ab_test` method available to all specs:
RSpec.configure do |config|
config.include SplitHelper
end
```
Now you can call `use_ab_test(alternatives_by_experiment)` in your specs, for example:
```ruby
it "registers using experimental signup" do
use_ab_test experiment_name: "alternative_name"
post "/signups"
...
end
```
### Starting experiments manually
By default new A/B tests will be active right after deployment. In case you would like to start new test a while after
the deploy, you can do it by setting the `start_manually` configuration option to `true`.
After choosing this option tests won't be started right after deploy, but after pressing the `Start` button in Split admin dashboard. If a test is deleted from the Split dashboard, then it can only be started after pressing the `Start` button whenever being re-initialized.
### Reset after completion
When a user completes a test their session is reset so that they may start the test again in the future.
To stop this behaviour you can pass the following option to the `ab_finished` method:
```ruby
ab_finished(:experiment_name, reset: false)
```
The user will then always see the alternative they started with.
Any old unfinished experiment key will be deleted from the user's data storage if the experiment had been removed or is over and a winner had been chosen. This allows a user to enroll into any new experiment in cases when the `allow_multiple_experiments` config option is set to `false`.
### Reset experiments manually
By default Split automatically resets the experiment whenever it detects the configuration for an experiment has changed (e.g. you call `ab_test` with different alternatives). You can prevent this by setting the option `reset_manually` to `true`.
You may want to do this when you want to change something, like the variants' names, the metadata about an experiment, etc. without resetting everything.
### Multiple experiments at once
By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests.
To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = true
end
```
This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another.
To address this, setting the `allow_multiple_experiments` config option to 'control' like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = 'control'
end
```
For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment.
### Experiment Persistence
Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment.
By default Split will store the tests for each user in the session.
You can optionally configure Split to use a cookie, Redis, or any custom adapter of your choosing.
#### Cookies
```ruby
Split.configure do |config|
config.persistence = :cookie
end
```
When using the cookie persistence, Split stores data into an anonymous tracking cookie named 'split', which expires in 1 year. To change that, set the `persistence_cookie_length` in the configuration (unit of time in seconds).
```ruby
Split.configure do |config|
config.persistence = :cookie
config.persistence_cookie_length = 2592000 # 30 days
end
```
The data stored consists of the experiment name and the variants the user is in. Example: { "experiment_name" => "variant_a" }
__Note:__ Using cookies depends on `ActionDispatch::Cookies` or any identical API
#### Redis
Using Redis will allow ab_users to persist across sessions or machines.
```ruby
Split.configure do |config|
config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: -> (context) { context.current_user_id })
# Equivalent
# config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: :current_user_id)
end
```
Options:
* `lookup_by`: method to invoke per request for uniquely identifying ab_users (mandatory configuration)
* `namespace`: separate namespace to store these persisted values (default "persistence")
* `expire_seconds`: sets TTL for user key. (if a user is in multiple experiments most recent update will reset TTL for all their assignments)
#### Dual Adapter
The Dual Adapter allows the use of different persistence adapters for logged-in and logged-out users. A common use case is to use Redis for logged-in users and Cookies for logged-out users.
```ruby
cookie_adapter = Split::Persistence::CookieAdapter
redis_adapter = Split::Persistence::RedisAdapter.with_config(
lookup_by: -> (context) { context.send(:current_user).try(:id) },
expire_seconds: 2592000)
Split.configure do |config|
config.persistence = Split::Persistence::DualAdapter.with_config(
logged_in: -> (context) { !context.send(:current_user).try(:id).nil? },
logged_in_adapter: redis_adapter,
logged_out_adapter: cookie_adapter)
config.persistence_cookie_length = 2592000 # 30 days
end
```
#### Custom Adapter
Your custom adapter needs to implement the same API as existing adapters.
See `Split::Persistence::CookieAdapter` or `Split::Persistence::SessionAdapter` for a starting point.
```ruby
Split.configure do |config|
config.persistence = YourCustomAdapterClass
end
```
### Trial Event Hooks
You can define methods that will be called at the same time as experiment
alternative participation and goal completion.
For example:
``` ruby
Split.configure do |config|
config.on_trial = :log_trial # run on every trial
config.on_trial_choose = :log_trial_choose # run on trials with new users only
config.on_trial_complete = :log_trial_complete
end
```
Set these attributes to a method name available in the same context as the
`ab_test` method. These methods should accept one argument, a `Trial` instance.
``` ruby
def log_trial(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_choose(trial)
logger.info "[new user] experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_complete(trial)
logger.info "experiment=%s alternative=%s user=%s complete=true" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
#### Views
If you are running `ab_test` from a view, you must define your event
hook callback as a
[helper_method](https://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method)
in the controller:
``` ruby
helper_method :log_trial_choose
def log_trial_choose(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
### Experiment Hooks
You can assign a proc that will be called when an experiment is reset or deleted. You can use these hooks to call methods within your application to keep data related to experiments in sync with Split.
For example:
``` ruby
Split.configure do |config|
# after experiment reset or deleted
config.on_experiment_reset = -> (example) { # Do something on reset }
config.on_experiment_delete = -> (experiment) { # Do something else on delete }
# before experiment reset or deleted
config.on_before_experiment_reset = -> (example) { # Do something on reset }
config.on_before_experiment_delete = -> (experiment) { # Do something else on delete }
# after experiment winner had been set
config.on_experiment_winner_choose = -> (experiment) { # Do something on winner choose }
end
```
## Web Interface
Split comes with a Sinatra-based front end to get an overview of how your experiments are doing.
If you are running Rails 2: You can mount this inside your app using Rack::URLMap in your `config.ru`
```ruby
require 'split/dashboard'
run Rack::URLMap.new \
"/" => Your::App.new,
"/split" => Split::Dashboard.new
```
However, if you are using Rails 3 or higher: You can mount this inside your app routes by first adding this to the Gemfile:
```ruby
gem 'split', require: 'split/dashboard'
```
Then adding this to config/routes.rb
```ruby
mount Split::Dashboard, at: 'split'
```
You may want to password protect that page, you can do so with `Rack::Auth::Basic` (in your split initializer file)
```ruby
# Rails apps or apps that already depend on activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
alternatives:
- a
- b
meta:
a:
text: "Have a fantastic day"
b:
text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
```
You can even use Devise or any other Warden-based authentication method to authorize users. Just replace `mount Split::Dashboard, :at => 'split'` in `config/routes.rb` with the following:
```ruby
match "/split" => Split::Dashboard, anchor: false, via: [:get, :post, :delete], constraints: -> (request) do
request.env['warden'].authenticated? # are we authenticated?
request.env['warden'].authenticate! # authenticate if not already
# or even check any other condition such as request.env['warden'].user.is_admin?
end
```
More information on this [here](https://steve.dynedge.co.uk/2011/12/09/controlling-access-to-routes-and-rack-apps-in-rails-3-with-devise-and-warden/)
### Screenshot

## Configuration
You can override the default configuration options of Split like so:
```ruby
Split.configure do |config|
config.db_failover = true # handle Redis errors gracefully
config.db_failover_on_db_error = -> (error) { Rails.logger.error(error.message) }
config.allow_multiple_experiments = true
config.enabled = true
config.persistence = Split::Persistence::SessionAdapter
#config.start_manually = false ## new test will have to be started manually from the admin panel. default false
#config.reset_manually = false ## if true, it never resets the experiment data, even if the configuration changes
config.include_rails_helper = true
config.redis = "redis://custom.redis.url:6380"
end
```
Split looks for the Redis host in the environment variable `REDIS_URL` then
defaults to `redis://localhost:6379` if not specified by configure block.
On platforms like Heroku, Split will use the value of `REDIS_PROVIDER` to
determine which env variable key to use when retrieving the host config. This
defaults to `REDIS_URL`.
### Filtering
In most scenarios you don't want to have AB-Testing enabled for web spiders, robots or special groups of users.
Split provides functionality to filter this based on a predefined, extensible list of bots, IP-lists or custom exclude logic.
```ruby
Split.configure do |config|
# bot config
config.robot_regex = /my_custom_robot_regex/ # or
config.bots['newbot'] = "Description for bot with 'newbot' user agent, which will be added to config.robot_regex for exclusion"
# IP config
config.ignore_ip_addresses << '81.19.48.130' # or regex: /81\.19\.48\.[0-9]+/
# or provide your own filter functionality, the default is proc{ |request| is_robot? || is_ignored_ip_address? || is_preview? }
config.ignore_filter = -> (request) { CustomExcludeLogic.excludes?(request) }
end
```
### Experiment configuration
Instead of providing the experiment options inline, you can store them
in a hash. This hash can control your experiment's alternatives, weights,
algorithm and if the experiment resets once finished:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
resettable: false
},
:my_second_experiment => {
algorithm: 'Split::Algorithms::Whiplash',
alternatives: [
{ name: "a", percent: 67 },
{ name: "b", percent: 33 }
]
}
}
end
```
You can also store your experiments in a YAML file:
```ruby
Split.configure do |config|
config.experiments = YAML.load_file "config/experiments.yml"
end
```
You can then define the YAML file like:
```yaml
my_first_experiment:
alternatives:
- a
- b
my_second_experiment:
alternatives:
- name: a
percent: 67
- name: b
percent: 33
resettable: false
```
This simplifies the calls from your code:
```ruby
ab_test(:my_first_experiment)
```
and:
```ruby
ab_finished(:my_first_experiment)
```
You can also add meta data for each experiment, which is very useful when you need more than an alternative name to change behaviour:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metadata: {
"a" => {"text" => "Have a fantastic day"},
"b" => {"text" => "Don't get hit by a bus"}
}
}
}
end
```
```yaml
my_first_experiment:
alternatives:
- a
- b
metadata:
a:
text: "Have a fantastic day"
b:
text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
```ruby
trial.alternative.name # => "a"
trial.metadata['text'] # => "Have a fantastic day"
```
or in views:
```erb
<% ab_test("my_first_experiment") do |alternative, meta| %>
<%= alternative %>
<small><%= meta['text'] %></small>
<% end %>
```
The keys used in meta data should be Strings
#### Metrics
You might wish to track generic metrics, such as conversions, and use
those to complete multiple different experiments without adding more to
your code. You can use the configuration hash to do this, thanks to
the `:metric` option.
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metric: :my_metric
}
}
end
```
Your code may then track a completion using the metric instead of
the experiment name:
```ruby
ab_finished(:my_metric)
```
You can also create a new metric by instantiating and saving a new Metric object.
```ruby
Split::Metric.new(:my_metric)
Split::Metric.save
```
#### Goals
You might wish to allow an experiment to have multiple, distinguishable goals.
The API to define goals for an experiment is this:
```ruby
ab_test({link_color: ["purchase", "refund"]}, "red", "blue")
```
or you can define them in a configuration file:
```ruby
Split.configure do |config|
config.experiments = {
link_color: {
alternatives: ["red", "blue"],
goals: ["purchase", "refund"]
}
}
end
```
To complete a goal conversion, you do it like:
```ruby
ab_finished(link_color: "purchase")
```
Note that if you pass additional options, that should be a separate hash:
```ruby
ab_finished({ link_color: "purchase" }, reset: false)
```
**NOTE:** This does not mean that a single experiment can complete more than one goal.
Once you finish one of the goals, the test is considered to be completed, and finishing the other goal will no longer register. (Assuming the test runs with `reset: false`.)
**Good Example**: Test if listing Plan A first result in more conversions to Plan A (goal: "plana_conversion") or Plan B (goal: "planb_conversion").
**Bad Example**: Test if button color increases conversion rate through multiple steps of a funnel. THIS WILL NOT WORK.
**Bad Example**: Test both how button color affects signup *and* how it affects login, at the same time. THIS WILL NOT WORK.
#### Combined Experiments
If you want to test how button color affects signup *and* how it affects login at the same time, use combined experiments.
Configure like so:
```ruby
Split.configuration.experiments = {
:button_color_experiment => {
:alternatives => ["blue", "green"],
:combined_experiments => ["button_color_on_signup", "button_color_on_login"]
}
}
```
Starting the combined test starts all combined experiments
```ruby
ab_combined_test(:button_color_experiment)
```
Finish each combined test as normal
```ruby
ab_finished(:button_color_on_login)
ab_finished(:button_color_on_signup)
```
**Additional Configuration**:
* Be sure to enable `allow_multiple_experiments`
* In Sinatra include the CombinedExperimentsHelper
```
helpers Split::CombinedExperimentsHelper
```
### DB failover solution
Due to the fact that Redis has no automatic failover mechanism, it's
possible to switch on the `db_failover` config option, so that `ab_test`
and `ab_finished` will not crash in case of a db failure. `ab_test` always
delivers alternative A (the first one) in that case.
It's also possible to set a `db_failover_on_db_error` callback (proc)
for example to log these errors via Rails.logger.
### Redis
You may want to change the Redis host and port Split connects to, or
set various other options at startup.
Split has a `redis` setter which can be given a string or a Redis
object. This means if you're already using Redis in your app, Split
can re-use the existing connection.
String: `Split.redis = 'redis://localhost:6379'`
Redis: `Split.redis = $redis`
For our rails app we have a `config/initializers/split.rb` file where
we load `config/split.yml` by hand and set the Redis information
appropriately.
Here's our `config/split.yml`:
```yml
development: redis://localhost:6379
test: redis://localhost:6379
staging: redis://redis1.example.com:6379
fi: redis://localhost:6379
production: redis://redis1.example.com:6379
```
And our initializer:
```ruby
split_config = YAML.load_file(Rails.root.join('config', 'split.yml'))
Split.redis = split_config[Rails.env]
```
### Redis Caching (v4.0+)
In some high-volume usage scenarios, Redis load can be incurred by repeated
fetches for fairly static data. Enabling caching will reduce this load.
```ruby
Split.configuration.cache = true
````
This currently caches:
- `Split::ExperimentCatalog.find`
- `Split::Experiment.start_time`
- `Split::Experiment.winner`
## Namespaces
If you're running multiple, separate instances of Split you may want
to namespace the keyspaces so they do not overlap. This is not unlike
the approach taken by many memcached clients.
This feature can be provided by the [redis-namespace](https://github.com/defunkt/redis-namespace)
library. To configure Split to use `Redis::Namespace`, do the following:
1. Add `redis-namespace` to your Gemfile:
```ruby
gem 'redis-namespace'
```
2. Configure `Split.redis` to use a `Redis::Namespace` instance (possible in an
initializer):
```ruby
redis = Redis.new(url: ENV['REDIS_URL']) # or whatever config you want
Split.redis = Redis::Namespace.new(:your_namespace, redis: redis)
```
## Outside of a Web Session
Split provides the Helper module to facilitate running experiments inside web sessions.
Alternatively, you can access the underlying Metric, Trial, Experiment and Alternative objects to
conduct experiments that are not tied to a web session.
```ruby
# create a new experiment
experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue')
# create a new trial
trial = Split::Trial.new(:experiment => experiment)
# run trial
trial.choose!
# get the result, returns either red or blue
trial.alternative.name
# if the goal has been achieved, increment the successful completions for this alternative.
if goal_achieved?
trial.complete!
end
```
## Algorithms
By default, Split ships with `Split::Algorithms::WeightedSample` that randomly selects from possible alternatives for a traditional a/b test.
It is possible to specify static weights to favor certain alternatives.
`Split::Algorithms::Whiplash` is an implementation of a [multi-armed bandit algorithm](http://stevehanov.ca/blog/index.php?id=132).
This algorithm will automatically weight the alternatives based on their relative performance,
choosing the better-performing ones more often as trials are completed.
`Split::Algorithms::BlockRandomization` is an algorithm that ensures equal
participation across all alternatives. This algorithm will choose the alternative
with the fewest participants. In the event of multiple minimum participant alternatives
(i.e. starting a new "Block") the algorithm will choose a random alternative from
those minimum participant alternatives.
Users may also write their own algorithms. The default algorithm may be specified globally in the configuration file, or on a per experiment basis using the experiments hash of the configuration file.
To change the algorithm globally for all experiments, use the following in your initializer:
```ruby
Split.configure do |config|
config.algorithm = Split::Algorithms::Whiplash
end
```
## Extensions
- [Split::Export](https://github.com/splitrb/split-export) - Easily export A/B test data out of Split.
- [Split::Analytics](https://github.com/splitrb/split-analytics) - Push test data to Google Analytics.
- [Split::Mongoid](https://github.com/MongoHQ/split-mongoid) - Store experiment data in mongoid (still uses redis).
- [Split::Cacheable](https://github.com/harrystech/split_cacheable) - Automatically create cache buckets per test.
- [Split::Counters](https://github.com/bernardkroes/split-counters) - Add counters per experiment and alternative.
- [Split::Cli](https://github.com/craigmcnamara/split-cli) - A CLI to trigger Split A/B tests.
## Screencast
Ryan bates has produced an excellent 10 minute screencast about split on the Railscasts site: [A/B Testing with Split](http://railscasts.com/episodes/331-a-b-testing-with-split)
## Blogposts
* [Recipe: A/B testing with KISSMetrics and the split gem](https://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem)
* [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html)
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/split#backer)]
<a href="https://opencollective.com/split/backer/0/website" target="_blank"><img src="https://opencollective.com/split/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/1/website" target="_blank"><img src="https://opencollective.com/split/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/2/website" target="_blank"><img src="https://opencollective.com/split/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/3/website" target="_blank"><img src="https://opencollective.com/split/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/4/website" target="_blank"><img src="https://opencollective.com/split/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/5/website" target="_blank"><img src="https://opencollective.com/split/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/6/website" target="_blank"><img src="https://opencollective.com/split/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/7/website" target="_blank"><img src="https://opencollective.com/split/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/8/website" target="_blank"><img src="https://opencollective.com/split/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/9/website" target="_blank"><img src="https://opencollective.com/split/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/10/website" target="_blank"><img src="https://opencollective.com/split/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/11/website" target="_blank"><img src="https://opencollective.com/split/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/12/website" target="_blank"><img src="https://opencollective.com/split/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/13/website" target="_blank"><img src="https://opencollective.com/split/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/14/website" target="_blank"><img src="https://opencollective.com/split/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/15/website" target="_blank"><img src="https://opencollective.com/split/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/16/website" target="_blank"><img src="https://opencollective.com/split/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/17/website" target="_blank"><img src="https://opencollective.com/split/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/18/website" target="_blank"><img src="https://opencollective.com/split/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/19/website" target="_blank"><img src="https://opencollective.com/split/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/20/website" target="_blank"><img src="https://opencollective.com/split/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/21/website" target="_blank"><img src="https://opencollective.com/split/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/22/website" target="_blank"><img src="https://opencollective.com/split/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/23/website" target="_blank"><img src="https://opencollective.com/split/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/24/website" target="_blank"><img src="https://opencollective.com/split/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/25/website" target="_blank"><img src="https://opencollective.com/split/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/26/website" target="_blank"><img src="https://opencollective.com/split/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/27/website" target="_blank"><img src="https://opencollective.com/split/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/28/website" target="_blank"><img src="https://opencollective.com/split/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/29/website" target="_blank"><img src="https://opencollective.com/split/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/split#sponsor)]
<a href="https://opencollective.com/split/sponsor/0/website" target="_blank"><img src="https://opencollective.com/split/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/1/website" target="_blank"><img src="https://opencollective.com/split/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/2/website" target="_blank"><img src="https://opencollective.com/split/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/3/website" target="_blank"><img src="https://opencollective.com/split/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/4/website" target="_blank"><img src="https://opencollective.com/split/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/5/website" target="_blank"><img src="https://opencollective.com/split/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/6/website" target="_blank"><img src="https://opencollective.com/split/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/7/website" target="_blank"><img src="https://opencollective.com/split/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/8/website" target="_blank"><img src="https://opencollective.com/split/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/9/website" target="_blank"><img src="https://opencollective.com/split/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/10/website" target="_blank"><img src="https://opencollective.com/split/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/11/website" target="_blank"><img src="https://opencollective.com/split/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/12/website" target="_blank"><img src="https://opencollective.com/split/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/13/website" target="_blank"><img src="https://opencollective.com/split/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/14/website" target="_blank"><img src="https://opencollective.com/split/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/15/website" target="_blank"><img src="https://opencollective.com/split/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/16/website" target="_blank"><img src="https://opencollective.com/split/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/17/website" target="_blank"><img src="https://opencollective.com/split/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/18/website" target="_blank"><img src="https://opencollective.com/split/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/19/website" target="_blank"><img src="https://opencollective.com/split/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/20/website" target="_blank"><img src="https://opencollective.com/split/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/21/website" target="_blank"><img src="https://opencollective.com/split/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/22/website" target="_blank"><img src="https://opencollective.com/split/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/23/website" target="_blank"><img src="https://opencollective.com/split/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/24/website" target="_blank"><img src="https://opencollective.com/split/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/25/website" target="_blank"><img src="https://opencollective.com/split/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/26/website" target="_blank"><img src="https://opencollective.com/split/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/27/website" target="_blank"><img src="https://opencollective.com/split/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/28/website" target="_blank"><img src="https://opencollective.com/split/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/29/website" target="_blank"><img src="https://opencollective.com/split/sponsor/29/avatar.svg"></a>
## Contribute
Please do! Over 70 different people have contributed to the project, you can see them all here: https://github.com/splitrb/split/graphs/contributors.
### Development
The source code is hosted at [GitHub](https://github.com/splitrb/split).
Report issues and feature requests on [GitHub Issues](https://github.com/splitrb/split/issues).
You can find a discussion form on [Google Groups](https://groups.google.com/d/forum/split-ruby).
### Tests
Run the tests like this:
# Start a Redis server in another tab.
redis-server
bundle
rake spec
### A Note on Patches and Pull Requests
* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
future version unintentionally.
* Add documentation if necessary.
* Commit. Do not mess with the rakefile, version, or history.
(If you want to have your own version, that is fine. But bump the version in a commit by itself, which I can ignore when I pull.)
* Send a pull request. Bonus points for topic branches.
### Code of Conduct
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
## Copyright
[MIT License](LICENSE) © 2019 [Andrew Nesbitt](https://github.com/andrew).
<MSG> Fixes experiment metadata doc
<DFF> @@ -435,11 +435,11 @@ my_first_experiment:
alternatives:
- a
- b
- meta:
- a:
- text: "Have a fantastic day"
- b:
- text: "Don't get hit by a bus"
+ metadata:
+ a:
+ text: "Have a fantastic day"
+ b:
+ text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
| 5 | Fixes experiment metadata doc | 5 | .md | md | mit | splitrb/split |
10071379 | <NME> README.md
<BEF> # [Split](https://libraries.io/rubygems/split)
[](http://badge.fury.io/rb/split)

[](https://codeclimate.com/github/splitrb/split)
[](https://codeclimate.com/github/splitrb/split/coverage)
[](https://github.com/RichardLitt/standard-readme)
[](https://www.codetriage.com/splitrb/split)
> 📈 The Rack Based A/B testing framework https://libraries.io/rubygems/split
Split is a rack based A/B testing framework designed to work with Rails, Sinatra or any other rack based app.
Split is heavily inspired by the [Abingo](https://github.com/ryanb/abingo) and [Vanity](https://github.com/assaf/vanity) Rails A/B testing plugins and [Resque](https://github.com/resque/resque) in its use of Redis.
Split is designed to be hacker friendly, allowing for maximum customisation and extensibility.
## Install
### Requirements
Split v4.0+ is currently tested with Ruby >= 2.5 and Rails >= 5.2.
If your project requires compatibility with Ruby 2.4.x or older Rails versions. You can try v3.0 or v0.8.0(for Ruby 1.9.3)
Split uses Redis as a datastore.
Split only supports Redis 4.0 or greater.
If you're on OS X, Homebrew is the simplest way to install Redis:
```bash
brew install redis
redis-server /usr/local/etc/redis.conf
```
You now have a Redis daemon running on port `6379`.
### Setup
```bash
gem install split
```
#### Rails
Adding `gem 'split'` to your Gemfile will autoload it when rails starts up, as long as you've configured Redis it will 'just work'.
#### Sinatra
To configure Sinatra with Split you need to enable sessions and mix in the helper methods. Add the following lines at the top of your Sinatra app:
```ruby
require 'split'
class MySinatraApp < Sinatra::Base
enable :sessions
helpers Split::Helper
get '/' do
...
end
```
## Usage
To begin your A/B test use the `ab_test` method, naming your experiment with the first argument and then the different alternatives which you wish to test on as the other arguments.
`ab_test` returns one of the alternatives, if a user has already seen that test they will get the same alternative as before, which you can use to split your code on.
It can be used to render different templates, show different text or any other case based logic.
`ab_finished` is used to make a completion of an experiment, or conversion.
Example: View
```erb
<% ab_test(:login_button, "/images/button1.jpg", "/images/button2.jpg") do |button_file| %>
<%= image_tag(button_file, alt: "Login!") %>
<% end %>
```
Example: Controller
```ruby
def register_new_user
# See what level of free points maximizes users' decision to buy replacement points.
@starter_points = ab_test(:new_user_free_points, '100', '200', '300')
end
```
Example: Conversion tracking (in a controller!)
```ruby
def buy_new_points
# some business logic
ab_finished(:new_user_free_points)
end
```
Example: Conversion tracking (in a view)
```erb
Thanks for signing up, dude! <% ab_finished(:signup_page_redesign) %>
```
You can find more examples, tutorials and guides on the [wiki](https://github.com/splitrb/split/wiki).
## Statistical Validity
Split has two options for you to use to determine which alternative is the best.
The first option (default on the dashboard) uses a z test (n>30) for the difference between your control and alternative conversion rates to calculate statistical significance. This test will tell you whether an alternative is better or worse than your control, but it will not distinguish between which alternative is the best in an experiment with multiple alternatives. Split will only tell you if your experiment is 90%, 95%, or 99% significant, and this test only works if you have more than 30 participants and 5 conversions for each branch.
As per this [blog post](https://www.evanmiller.org/how-not-to-run-an-ab-test.html) on the pitfalls of A/B testing, it is highly recommended that you determine your requisite sample size for each branch before running the experiment. Otherwise, you'll have an increased rate of false positives (experiments which show a significant effect where really there is none).
[Here](https://www.evanmiller.org/ab-testing/sample-size.html) is a sample size calculator for your convenience.
The second option uses simulations from a beta distribution to determine the probability that the given alternative is the winner compared to all other alternatives. You can view these probabilities by clicking on the drop-down menu labeled "Confidence." This option should be used when the experiment has more than just 1 control and 1 alternative. It can also be used for a simple, 2-alternative A/B test.
Calculating the beta-distribution simulations for a large number of experiments can be slow, so the results are cached. You can specify how often they should be recalculated (the default is once per day).
```ruby
Split.configure do |config|
config.winning_alternative_recalculation_interval = 3600 # 1 hour
end
```
## Extras
### Weighted alternatives
Perhaps you only want to show an alternative to 10% of your visitors because it is very experimental or not yet fully load tested.
To do this you can pass a weight with each alternative in the following ways:
```ruby
ab_test(:homepage_design, {'Old' => 18}, {'New' => 2})
ab_test(:homepage_design, 'Old', {'New' => 1.0/9})
ab_test(:homepage_design, {'Old' => 9}, 'New')
```
This will only show the new alternative to visitors 1 in 10 times, the default weight for an alternative is 1.
### Overriding alternatives
For development and testing, you may wish to force your app to always return an alternative.
You can do this by passing it as a parameter in the url.
If you have an experiment called `button_color` with alternatives called `red` and `blue` used on your homepage, a url such as:
http://myawesomesite.com?ab_test[button_color]=red
will always have red buttons. This won't be stored in your session or count towards to results, unless you set the `store_override` configuration option.
In the event you want to disable all tests without having to know the individual experiment names, add a `SPLIT_DISABLE` query parameter.
http://myawesomesite.com?SPLIT_DISABLE=true
It is not required to send `SPLIT_DISABLE=false` to activate Split.
### Rspec Helper
To aid testing with RSpec, write `spec/support/split_helper.rb` and call `use_ab_test(alternatives_by_experiment)` in your specs as instructed below:
```ruby
# Create a file with these contents at 'spec/support/split_helper.rb'
# and ensure it is `require`d in your rails_helper.rb or spec_helper.rb
module SplitHelper
# Force a specific experiment alternative to always be returned:
# use_ab_test(signup_form: "single_page")
#
# Force alternatives for multiple experiments:
# use_ab_test(signup_form: "single_page", pricing: "show_enterprise_prices")
#
def use_ab_test(alternatives_by_experiment)
allow_any_instance_of(Split::Helper).to receive(:ab_test) do |_receiver, experiment, &block|
variant = alternatives_by_experiment.fetch(experiment) { |key| raise "Unknown experiment '#{key}'" }
block.call(variant) unless block.nil?
variant
end
end
end
# Make the `use_ab_test` method available to all specs:
RSpec.configure do |config|
config.include SplitHelper
end
```
Now you can call `use_ab_test(alternatives_by_experiment)` in your specs, for example:
```ruby
it "registers using experimental signup" do
use_ab_test experiment_name: "alternative_name"
post "/signups"
...
end
```
### Starting experiments manually
By default new A/B tests will be active right after deployment. In case you would like to start new test a while after
the deploy, you can do it by setting the `start_manually` configuration option to `true`.
After choosing this option tests won't be started right after deploy, but after pressing the `Start` button in Split admin dashboard. If a test is deleted from the Split dashboard, then it can only be started after pressing the `Start` button whenever being re-initialized.
### Reset after completion
When a user completes a test their session is reset so that they may start the test again in the future.
To stop this behaviour you can pass the following option to the `ab_finished` method:
```ruby
ab_finished(:experiment_name, reset: false)
```
The user will then always see the alternative they started with.
Any old unfinished experiment key will be deleted from the user's data storage if the experiment had been removed or is over and a winner had been chosen. This allows a user to enroll into any new experiment in cases when the `allow_multiple_experiments` config option is set to `false`.
### Reset experiments manually
By default Split automatically resets the experiment whenever it detects the configuration for an experiment has changed (e.g. you call `ab_test` with different alternatives). You can prevent this by setting the option `reset_manually` to `true`.
You may want to do this when you want to change something, like the variants' names, the metadata about an experiment, etc. without resetting everything.
### Multiple experiments at once
By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests.
To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = true
end
```
This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another.
To address this, setting the `allow_multiple_experiments` config option to 'control' like so:
```ruby
Split.configure do |config|
config.allow_multiple_experiments = 'control'
end
```
For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment.
### Experiment Persistence
Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment.
By default Split will store the tests for each user in the session.
You can optionally configure Split to use a cookie, Redis, or any custom adapter of your choosing.
#### Cookies
```ruby
Split.configure do |config|
config.persistence = :cookie
end
```
When using the cookie persistence, Split stores data into an anonymous tracking cookie named 'split', which expires in 1 year. To change that, set the `persistence_cookie_length` in the configuration (unit of time in seconds).
```ruby
Split.configure do |config|
config.persistence = :cookie
config.persistence_cookie_length = 2592000 # 30 days
end
```
The data stored consists of the experiment name and the variants the user is in. Example: { "experiment_name" => "variant_a" }
__Note:__ Using cookies depends on `ActionDispatch::Cookies` or any identical API
#### Redis
Using Redis will allow ab_users to persist across sessions or machines.
```ruby
Split.configure do |config|
config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: -> (context) { context.current_user_id })
# Equivalent
# config.persistence = Split::Persistence::RedisAdapter.with_config(lookup_by: :current_user_id)
end
```
Options:
* `lookup_by`: method to invoke per request for uniquely identifying ab_users (mandatory configuration)
* `namespace`: separate namespace to store these persisted values (default "persistence")
* `expire_seconds`: sets TTL for user key. (if a user is in multiple experiments most recent update will reset TTL for all their assignments)
#### Dual Adapter
The Dual Adapter allows the use of different persistence adapters for logged-in and logged-out users. A common use case is to use Redis for logged-in users and Cookies for logged-out users.
```ruby
cookie_adapter = Split::Persistence::CookieAdapter
redis_adapter = Split::Persistence::RedisAdapter.with_config(
lookup_by: -> (context) { context.send(:current_user).try(:id) },
expire_seconds: 2592000)
Split.configure do |config|
config.persistence = Split::Persistence::DualAdapter.with_config(
logged_in: -> (context) { !context.send(:current_user).try(:id).nil? },
logged_in_adapter: redis_adapter,
logged_out_adapter: cookie_adapter)
config.persistence_cookie_length = 2592000 # 30 days
end
```
#### Custom Adapter
Your custom adapter needs to implement the same API as existing adapters.
See `Split::Persistence::CookieAdapter` or `Split::Persistence::SessionAdapter` for a starting point.
```ruby
Split.configure do |config|
config.persistence = YourCustomAdapterClass
end
```
### Trial Event Hooks
You can define methods that will be called at the same time as experiment
alternative participation and goal completion.
For example:
``` ruby
Split.configure do |config|
config.on_trial = :log_trial # run on every trial
config.on_trial_choose = :log_trial_choose # run on trials with new users only
config.on_trial_complete = :log_trial_complete
end
```
Set these attributes to a method name available in the same context as the
`ab_test` method. These methods should accept one argument, a `Trial` instance.
``` ruby
def log_trial(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_choose(trial)
logger.info "[new user] experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
def log_trial_complete(trial)
logger.info "experiment=%s alternative=%s user=%s complete=true" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
#### Views
If you are running `ab_test` from a view, you must define your event
hook callback as a
[helper_method](https://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method)
in the controller:
``` ruby
helper_method :log_trial_choose
def log_trial_choose(trial)
logger.info "experiment=%s alternative=%s user=%s" %
[ trial.experiment.name, trial.alternative, current_user.id ]
end
```
### Experiment Hooks
You can assign a proc that will be called when an experiment is reset or deleted. You can use these hooks to call methods within your application to keep data related to experiments in sync with Split.
For example:
``` ruby
Split.configure do |config|
# after experiment reset or deleted
config.on_experiment_reset = -> (example) { # Do something on reset }
config.on_experiment_delete = -> (experiment) { # Do something else on delete }
# before experiment reset or deleted
config.on_before_experiment_reset = -> (example) { # Do something on reset }
config.on_before_experiment_delete = -> (experiment) { # Do something else on delete }
# after experiment winner had been set
config.on_experiment_winner_choose = -> (experiment) { # Do something on winner choose }
end
```
## Web Interface
Split comes with a Sinatra-based front end to get an overview of how your experiments are doing.
If you are running Rails 2: You can mount this inside your app using Rack::URLMap in your `config.ru`
```ruby
require 'split/dashboard'
run Rack::URLMap.new \
"/" => Your::App.new,
"/split" => Split::Dashboard.new
```
However, if you are using Rails 3 or higher: You can mount this inside your app routes by first adding this to the Gemfile:
```ruby
gem 'split', require: 'split/dashboard'
```
Then adding this to config/routes.rb
```ruby
mount Split::Dashboard, at: 'split'
```
You may want to password protect that page, you can do so with `Rack::Auth::Basic` (in your split initializer file)
```ruby
# Rails apps or apps that already depend on activesupport
Split::Dashboard.use Rack::Auth::Basic do |username, password|
# Protect against timing attacks:
# - Use & (do not use &&) so that it doesn't short circuit.
# - Use digests to stop length information leaking
ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SPLIT_USERNAME"])) &
alternatives:
- a
- b
meta:
a:
text: "Have a fantastic day"
b:
text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
```
You can even use Devise or any other Warden-based authentication method to authorize users. Just replace `mount Split::Dashboard, :at => 'split'` in `config/routes.rb` with the following:
```ruby
match "/split" => Split::Dashboard, anchor: false, via: [:get, :post, :delete], constraints: -> (request) do
request.env['warden'].authenticated? # are we authenticated?
request.env['warden'].authenticate! # authenticate if not already
# or even check any other condition such as request.env['warden'].user.is_admin?
end
```
More information on this [here](https://steve.dynedge.co.uk/2011/12/09/controlling-access-to-routes-and-rack-apps-in-rails-3-with-devise-and-warden/)
### Screenshot

## Configuration
You can override the default configuration options of Split like so:
```ruby
Split.configure do |config|
config.db_failover = true # handle Redis errors gracefully
config.db_failover_on_db_error = -> (error) { Rails.logger.error(error.message) }
config.allow_multiple_experiments = true
config.enabled = true
config.persistence = Split::Persistence::SessionAdapter
#config.start_manually = false ## new test will have to be started manually from the admin panel. default false
#config.reset_manually = false ## if true, it never resets the experiment data, even if the configuration changes
config.include_rails_helper = true
config.redis = "redis://custom.redis.url:6380"
end
```
Split looks for the Redis host in the environment variable `REDIS_URL` then
defaults to `redis://localhost:6379` if not specified by configure block.
On platforms like Heroku, Split will use the value of `REDIS_PROVIDER` to
determine which env variable key to use when retrieving the host config. This
defaults to `REDIS_URL`.
### Filtering
In most scenarios you don't want to have AB-Testing enabled for web spiders, robots or special groups of users.
Split provides functionality to filter this based on a predefined, extensible list of bots, IP-lists or custom exclude logic.
```ruby
Split.configure do |config|
# bot config
config.robot_regex = /my_custom_robot_regex/ # or
config.bots['newbot'] = "Description for bot with 'newbot' user agent, which will be added to config.robot_regex for exclusion"
# IP config
config.ignore_ip_addresses << '81.19.48.130' # or regex: /81\.19\.48\.[0-9]+/
# or provide your own filter functionality, the default is proc{ |request| is_robot? || is_ignored_ip_address? || is_preview? }
config.ignore_filter = -> (request) { CustomExcludeLogic.excludes?(request) }
end
```
### Experiment configuration
Instead of providing the experiment options inline, you can store them
in a hash. This hash can control your experiment's alternatives, weights,
algorithm and if the experiment resets once finished:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
resettable: false
},
:my_second_experiment => {
algorithm: 'Split::Algorithms::Whiplash',
alternatives: [
{ name: "a", percent: 67 },
{ name: "b", percent: 33 }
]
}
}
end
```
You can also store your experiments in a YAML file:
```ruby
Split.configure do |config|
config.experiments = YAML.load_file "config/experiments.yml"
end
```
You can then define the YAML file like:
```yaml
my_first_experiment:
alternatives:
- a
- b
my_second_experiment:
alternatives:
- name: a
percent: 67
- name: b
percent: 33
resettable: false
```
This simplifies the calls from your code:
```ruby
ab_test(:my_first_experiment)
```
and:
```ruby
ab_finished(:my_first_experiment)
```
You can also add meta data for each experiment, which is very useful when you need more than an alternative name to change behaviour:
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metadata: {
"a" => {"text" => "Have a fantastic day"},
"b" => {"text" => "Don't get hit by a bus"}
}
}
}
end
```
```yaml
my_first_experiment:
alternatives:
- a
- b
metadata:
a:
text: "Have a fantastic day"
b:
text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
```ruby
trial.alternative.name # => "a"
trial.metadata['text'] # => "Have a fantastic day"
```
or in views:
```erb
<% ab_test("my_first_experiment") do |alternative, meta| %>
<%= alternative %>
<small><%= meta['text'] %></small>
<% end %>
```
The keys used in meta data should be Strings
#### Metrics
You might wish to track generic metrics, such as conversions, and use
those to complete multiple different experiments without adding more to
your code. You can use the configuration hash to do this, thanks to
the `:metric` option.
```ruby
Split.configure do |config|
config.experiments = {
my_first_experiment: {
alternatives: ["a", "b"],
metric: :my_metric
}
}
end
```
Your code may then track a completion using the metric instead of
the experiment name:
```ruby
ab_finished(:my_metric)
```
You can also create a new metric by instantiating and saving a new Metric object.
```ruby
Split::Metric.new(:my_metric)
Split::Metric.save
```
#### Goals
You might wish to allow an experiment to have multiple, distinguishable goals.
The API to define goals for an experiment is this:
```ruby
ab_test({link_color: ["purchase", "refund"]}, "red", "blue")
```
or you can define them in a configuration file:
```ruby
Split.configure do |config|
config.experiments = {
link_color: {
alternatives: ["red", "blue"],
goals: ["purchase", "refund"]
}
}
end
```
To complete a goal conversion, you do it like:
```ruby
ab_finished(link_color: "purchase")
```
Note that if you pass additional options, that should be a separate hash:
```ruby
ab_finished({ link_color: "purchase" }, reset: false)
```
**NOTE:** This does not mean that a single experiment can complete more than one goal.
Once you finish one of the goals, the test is considered to be completed, and finishing the other goal will no longer register. (Assuming the test runs with `reset: false`.)
**Good Example**: Test if listing Plan A first result in more conversions to Plan A (goal: "plana_conversion") or Plan B (goal: "planb_conversion").
**Bad Example**: Test if button color increases conversion rate through multiple steps of a funnel. THIS WILL NOT WORK.
**Bad Example**: Test both how button color affects signup *and* how it affects login, at the same time. THIS WILL NOT WORK.
#### Combined Experiments
If you want to test how button color affects signup *and* how it affects login at the same time, use combined experiments.
Configure like so:
```ruby
Split.configuration.experiments = {
:button_color_experiment => {
:alternatives => ["blue", "green"],
:combined_experiments => ["button_color_on_signup", "button_color_on_login"]
}
}
```
Starting the combined test starts all combined experiments
```ruby
ab_combined_test(:button_color_experiment)
```
Finish each combined test as normal
```ruby
ab_finished(:button_color_on_login)
ab_finished(:button_color_on_signup)
```
**Additional Configuration**:
* Be sure to enable `allow_multiple_experiments`
* In Sinatra include the CombinedExperimentsHelper
```
helpers Split::CombinedExperimentsHelper
```
### DB failover solution
Due to the fact that Redis has no automatic failover mechanism, it's
possible to switch on the `db_failover` config option, so that `ab_test`
and `ab_finished` will not crash in case of a db failure. `ab_test` always
delivers alternative A (the first one) in that case.
It's also possible to set a `db_failover_on_db_error` callback (proc)
for example to log these errors via Rails.logger.
### Redis
You may want to change the Redis host and port Split connects to, or
set various other options at startup.
Split has a `redis` setter which can be given a string or a Redis
object. This means if you're already using Redis in your app, Split
can re-use the existing connection.
String: `Split.redis = 'redis://localhost:6379'`
Redis: `Split.redis = $redis`
For our rails app we have a `config/initializers/split.rb` file where
we load `config/split.yml` by hand and set the Redis information
appropriately.
Here's our `config/split.yml`:
```yml
development: redis://localhost:6379
test: redis://localhost:6379
staging: redis://redis1.example.com:6379
fi: redis://localhost:6379
production: redis://redis1.example.com:6379
```
And our initializer:
```ruby
split_config = YAML.load_file(Rails.root.join('config', 'split.yml'))
Split.redis = split_config[Rails.env]
```
### Redis Caching (v4.0+)
In some high-volume usage scenarios, Redis load can be incurred by repeated
fetches for fairly static data. Enabling caching will reduce this load.
```ruby
Split.configuration.cache = true
````
This currently caches:
- `Split::ExperimentCatalog.find`
- `Split::Experiment.start_time`
- `Split::Experiment.winner`
## Namespaces
If you're running multiple, separate instances of Split you may want
to namespace the keyspaces so they do not overlap. This is not unlike
the approach taken by many memcached clients.
This feature can be provided by the [redis-namespace](https://github.com/defunkt/redis-namespace)
library. To configure Split to use `Redis::Namespace`, do the following:
1. Add `redis-namespace` to your Gemfile:
```ruby
gem 'redis-namespace'
```
2. Configure `Split.redis` to use a `Redis::Namespace` instance (possible in an
initializer):
```ruby
redis = Redis.new(url: ENV['REDIS_URL']) # or whatever config you want
Split.redis = Redis::Namespace.new(:your_namespace, redis: redis)
```
## Outside of a Web Session
Split provides the Helper module to facilitate running experiments inside web sessions.
Alternatively, you can access the underlying Metric, Trial, Experiment and Alternative objects to
conduct experiments that are not tied to a web session.
```ruby
# create a new experiment
experiment = Split::ExperimentCatalog.find_or_create('color', 'red', 'blue')
# create a new trial
trial = Split::Trial.new(:experiment => experiment)
# run trial
trial.choose!
# get the result, returns either red or blue
trial.alternative.name
# if the goal has been achieved, increment the successful completions for this alternative.
if goal_achieved?
trial.complete!
end
```
## Algorithms
By default, Split ships with `Split::Algorithms::WeightedSample` that randomly selects from possible alternatives for a traditional a/b test.
It is possible to specify static weights to favor certain alternatives.
`Split::Algorithms::Whiplash` is an implementation of a [multi-armed bandit algorithm](http://stevehanov.ca/blog/index.php?id=132).
This algorithm will automatically weight the alternatives based on their relative performance,
choosing the better-performing ones more often as trials are completed.
`Split::Algorithms::BlockRandomization` is an algorithm that ensures equal
participation across all alternatives. This algorithm will choose the alternative
with the fewest participants. In the event of multiple minimum participant alternatives
(i.e. starting a new "Block") the algorithm will choose a random alternative from
those minimum participant alternatives.
Users may also write their own algorithms. The default algorithm may be specified globally in the configuration file, or on a per experiment basis using the experiments hash of the configuration file.
To change the algorithm globally for all experiments, use the following in your initializer:
```ruby
Split.configure do |config|
config.algorithm = Split::Algorithms::Whiplash
end
```
## Extensions
- [Split::Export](https://github.com/splitrb/split-export) - Easily export A/B test data out of Split.
- [Split::Analytics](https://github.com/splitrb/split-analytics) - Push test data to Google Analytics.
- [Split::Mongoid](https://github.com/MongoHQ/split-mongoid) - Store experiment data in mongoid (still uses redis).
- [Split::Cacheable](https://github.com/harrystech/split_cacheable) - Automatically create cache buckets per test.
- [Split::Counters](https://github.com/bernardkroes/split-counters) - Add counters per experiment and alternative.
- [Split::Cli](https://github.com/craigmcnamara/split-cli) - A CLI to trigger Split A/B tests.
## Screencast
Ryan bates has produced an excellent 10 minute screencast about split on the Railscasts site: [A/B Testing with Split](http://railscasts.com/episodes/331-a-b-testing-with-split)
## Blogposts
* [Recipe: A/B testing with KISSMetrics and the split gem](https://robots.thoughtbot.com/post/9595887299/recipe-a-b-testing-with-kissmetrics-and-the-split-gem)
* [Rails A/B testing with Split on Heroku](http://blog.nathanhumbert.com/2012/02/rails-ab-testing-with-split-on-heroku.html)
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/split#backer)]
<a href="https://opencollective.com/split/backer/0/website" target="_blank"><img src="https://opencollective.com/split/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/1/website" target="_blank"><img src="https://opencollective.com/split/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/2/website" target="_blank"><img src="https://opencollective.com/split/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/3/website" target="_blank"><img src="https://opencollective.com/split/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/4/website" target="_blank"><img src="https://opencollective.com/split/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/5/website" target="_blank"><img src="https://opencollective.com/split/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/6/website" target="_blank"><img src="https://opencollective.com/split/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/7/website" target="_blank"><img src="https://opencollective.com/split/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/8/website" target="_blank"><img src="https://opencollective.com/split/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/9/website" target="_blank"><img src="https://opencollective.com/split/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/10/website" target="_blank"><img src="https://opencollective.com/split/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/11/website" target="_blank"><img src="https://opencollective.com/split/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/12/website" target="_blank"><img src="https://opencollective.com/split/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/13/website" target="_blank"><img src="https://opencollective.com/split/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/14/website" target="_blank"><img src="https://opencollective.com/split/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/15/website" target="_blank"><img src="https://opencollective.com/split/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/16/website" target="_blank"><img src="https://opencollective.com/split/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/17/website" target="_blank"><img src="https://opencollective.com/split/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/18/website" target="_blank"><img src="https://opencollective.com/split/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/19/website" target="_blank"><img src="https://opencollective.com/split/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/20/website" target="_blank"><img src="https://opencollective.com/split/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/21/website" target="_blank"><img src="https://opencollective.com/split/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/22/website" target="_blank"><img src="https://opencollective.com/split/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/23/website" target="_blank"><img src="https://opencollective.com/split/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/24/website" target="_blank"><img src="https://opencollective.com/split/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/25/website" target="_blank"><img src="https://opencollective.com/split/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/26/website" target="_blank"><img src="https://opencollective.com/split/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/27/website" target="_blank"><img src="https://opencollective.com/split/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/28/website" target="_blank"><img src="https://opencollective.com/split/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/split/backer/29/website" target="_blank"><img src="https://opencollective.com/split/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/split#sponsor)]
<a href="https://opencollective.com/split/sponsor/0/website" target="_blank"><img src="https://opencollective.com/split/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/1/website" target="_blank"><img src="https://opencollective.com/split/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/2/website" target="_blank"><img src="https://opencollective.com/split/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/3/website" target="_blank"><img src="https://opencollective.com/split/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/4/website" target="_blank"><img src="https://opencollective.com/split/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/5/website" target="_blank"><img src="https://opencollective.com/split/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/6/website" target="_blank"><img src="https://opencollective.com/split/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/7/website" target="_blank"><img src="https://opencollective.com/split/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/8/website" target="_blank"><img src="https://opencollective.com/split/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/9/website" target="_blank"><img src="https://opencollective.com/split/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/10/website" target="_blank"><img src="https://opencollective.com/split/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/11/website" target="_blank"><img src="https://opencollective.com/split/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/12/website" target="_blank"><img src="https://opencollective.com/split/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/13/website" target="_blank"><img src="https://opencollective.com/split/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/14/website" target="_blank"><img src="https://opencollective.com/split/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/15/website" target="_blank"><img src="https://opencollective.com/split/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/16/website" target="_blank"><img src="https://opencollective.com/split/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/17/website" target="_blank"><img src="https://opencollective.com/split/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/18/website" target="_blank"><img src="https://opencollective.com/split/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/19/website" target="_blank"><img src="https://opencollective.com/split/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/20/website" target="_blank"><img src="https://opencollective.com/split/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/21/website" target="_blank"><img src="https://opencollective.com/split/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/22/website" target="_blank"><img src="https://opencollective.com/split/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/23/website" target="_blank"><img src="https://opencollective.com/split/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/24/website" target="_blank"><img src="https://opencollective.com/split/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/25/website" target="_blank"><img src="https://opencollective.com/split/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/26/website" target="_blank"><img src="https://opencollective.com/split/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/27/website" target="_blank"><img src="https://opencollective.com/split/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/28/website" target="_blank"><img src="https://opencollective.com/split/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/split/sponsor/29/website" target="_blank"><img src="https://opencollective.com/split/sponsor/29/avatar.svg"></a>
## Contribute
Please do! Over 70 different people have contributed to the project, you can see them all here: https://github.com/splitrb/split/graphs/contributors.
### Development
The source code is hosted at [GitHub](https://github.com/splitrb/split).
Report issues and feature requests on [GitHub Issues](https://github.com/splitrb/split/issues).
You can find a discussion form on [Google Groups](https://groups.google.com/d/forum/split-ruby).
### Tests
Run the tests like this:
# Start a Redis server in another tab.
redis-server
bundle
rake spec
### A Note on Patches and Pull Requests
* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
future version unintentionally.
* Add documentation if necessary.
* Commit. Do not mess with the rakefile, version, or history.
(If you want to have your own version, that is fine. But bump the version in a commit by itself, which I can ignore when I pull.)
* Send a pull request. Bonus points for topic branches.
### Code of Conduct
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
## Copyright
[MIT License](LICENSE) © 2019 [Andrew Nesbitt](https://github.com/andrew).
<MSG> Fixes experiment metadata doc
<DFF> @@ -435,11 +435,11 @@ my_first_experiment:
alternatives:
- a
- b
- meta:
- a:
- text: "Have a fantastic day"
- b:
- text: "Don't get hit by a bus"
+ metadata:
+ a:
+ text: "Have a fantastic day"
+ b:
+ text: "Don't get hit by a bus"
```
This allows for some advanced experiment configuration using methods like:
| 5 | Fixes experiment metadata doc | 5 | .md | md | mit | splitrb/split |
10071380 | <NME> trial.rb
<BEF> # frozen_string_literal: true
module Split
class Trial
attr_accessor :goals
attr_accessor :experiment
attr_writer :metadata
def initialize(attrs = {})
end
def alternative
@alternative ||= if experiment.winner
experiment.winner
end
end
@alternative_chosen = false
end
def metadata
@metadata ||= experiment.metadata[alternative.name] if experiment.metadata
end
def alternative
@alternative ||= if @experiment.has_winner?
@experiment.winner
end
end
def alternative=(alternative)
@alternative = if alternative.kind_of?(Split::Alternative)
alternative
else
@experiment.alternatives.find { |a| a.name == alternative }
end
end
def complete!(context = nil)
if alternative
if Array(goals).empty?
alternative.increment_completion
else
Array(goals).each { |g| alternative.increment_completion(g) }
end
run_callback context, Split.configuration.on_trial_complete
end
end
# Choose an alternative, add a participant, and save the alternative choice on the user. This
# method is guaranteed to only run once, and will skip the alternative choosing process if run
# a second time.
def choose!(context = nil)
@user.cleanup_old_experiments!
# Only run the process once
return alternative if @alternative_chosen
new_participant = @user[@experiment.key].nil?
if override_is_alternative?
self.alternative = @options[:override]
if should_store_alternative? && !@user[@experiment.key]
self.alternative.increment_participation
end
elsif @options[:disabled] || Split.configuration.disabled?
self.alternative = @experiment.control
elsif @experiment.has_winner?
self.alternative = @experiment.winner
else
cleanup_old_versions
if exclude_user?
self.alternative = @experiment.control
else
self.alternative = @user[@experiment.key]
if alternative.nil?
if @experiment.cohorting_disabled?
self.alternative = @experiment.control
else
self.alternative = @experiment.next_alternative
# Increment the number of participants since we are actually choosing a new alternative
self.alternative.increment_participation
run_callback context, Split.configuration.on_trial_choose
end
end
end
end
new_participant_and_cohorting_disabled = new_participant && @experiment.cohorting_disabled?
@user[@experiment.key] = alternative.name unless @experiment.has_winner? || !should_store_alternative? || new_participant_and_cohorting_disabled
@alternative_chosen = true
run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled? || new_participant_and_cohorting_disabled
alternative
end
private
def run_callback(context, callback_name)
context.send(callback_name, self) if callback_name && context.respond_to?(callback_name, true)
end
def override_is_alternative?
@experiment.alternatives.map(&:name).include?(@options[:override])
end
def should_store_alternative?
if @options[:override] || @options[:disabled]
Split.configuration.store_override
else
!exclude_user?
end
end
def cleanup_old_versions
if @experiment.version > 0
@user.cleanup_old_versions!(@experiment)
end
end
def exclude_user?
@options[:exclude] || @experiment.start_time.nil? || @user.max_experiments_reached?(@experiment.key)
end
end
end
<MSG> Replace winner existance checks with has_winner? to be more readable
<DFF> @@ -10,7 +10,7 @@ module Split
end
def alternative
- @alternative ||= if experiment.winner
+ @alternative ||= if experiment.has_winner?
experiment.winner
end
end
| 1 | Replace winner existance checks with has_winner? to be more readable | 1 | .rb | rb | mit | splitrb/split |
10071381 | <NME> trial.rb
<BEF> # frozen_string_literal: true
module Split
class Trial
attr_accessor :goals
attr_accessor :experiment
attr_writer :metadata
def initialize(attrs = {})
end
def alternative
@alternative ||= if experiment.winner
experiment.winner
end
end
@alternative_chosen = false
end
def metadata
@metadata ||= experiment.metadata[alternative.name] if experiment.metadata
end
def alternative
@alternative ||= if @experiment.has_winner?
@experiment.winner
end
end
def alternative=(alternative)
@alternative = if alternative.kind_of?(Split::Alternative)
alternative
else
@experiment.alternatives.find { |a| a.name == alternative }
end
end
def complete!(context = nil)
if alternative
if Array(goals).empty?
alternative.increment_completion
else
Array(goals).each { |g| alternative.increment_completion(g) }
end
run_callback context, Split.configuration.on_trial_complete
end
end
# Choose an alternative, add a participant, and save the alternative choice on the user. This
# method is guaranteed to only run once, and will skip the alternative choosing process if run
# a second time.
def choose!(context = nil)
@user.cleanup_old_experiments!
# Only run the process once
return alternative if @alternative_chosen
new_participant = @user[@experiment.key].nil?
if override_is_alternative?
self.alternative = @options[:override]
if should_store_alternative? && !@user[@experiment.key]
self.alternative.increment_participation
end
elsif @options[:disabled] || Split.configuration.disabled?
self.alternative = @experiment.control
elsif @experiment.has_winner?
self.alternative = @experiment.winner
else
cleanup_old_versions
if exclude_user?
self.alternative = @experiment.control
else
self.alternative = @user[@experiment.key]
if alternative.nil?
if @experiment.cohorting_disabled?
self.alternative = @experiment.control
else
self.alternative = @experiment.next_alternative
# Increment the number of participants since we are actually choosing a new alternative
self.alternative.increment_participation
run_callback context, Split.configuration.on_trial_choose
end
end
end
end
new_participant_and_cohorting_disabled = new_participant && @experiment.cohorting_disabled?
@user[@experiment.key] = alternative.name unless @experiment.has_winner? || !should_store_alternative? || new_participant_and_cohorting_disabled
@alternative_chosen = true
run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled? || new_participant_and_cohorting_disabled
alternative
end
private
def run_callback(context, callback_name)
context.send(callback_name, self) if callback_name && context.respond_to?(callback_name, true)
end
def override_is_alternative?
@experiment.alternatives.map(&:name).include?(@options[:override])
end
def should_store_alternative?
if @options[:override] || @options[:disabled]
Split.configuration.store_override
else
!exclude_user?
end
end
def cleanup_old_versions
if @experiment.version > 0
@user.cleanup_old_versions!(@experiment)
end
end
def exclude_user?
@options[:exclude] || @experiment.start_time.nil? || @user.max_experiments_reached?(@experiment.key)
end
end
end
<MSG> Replace winner existance checks with has_winner? to be more readable
<DFF> @@ -10,7 +10,7 @@ module Split
end
def alternative
- @alternative ||= if experiment.winner
+ @alternative ||= if experiment.has_winner?
experiment.winner
end
end
| 1 | Replace winner existance checks with has_winner? to be more readable | 1 | .rb | rb | mit | splitrb/split |
10071382 | <NME> trial.rb
<BEF> # frozen_string_literal: true
module Split
class Trial
attr_accessor :goals
attr_accessor :experiment
attr_writer :metadata
def initialize(attrs = {})
end
def alternative
@alternative ||= if experiment.winner
experiment.winner
end
end
@alternative_chosen = false
end
def metadata
@metadata ||= experiment.metadata[alternative.name] if experiment.metadata
end
def alternative
@alternative ||= if @experiment.has_winner?
@experiment.winner
end
end
def alternative=(alternative)
@alternative = if alternative.kind_of?(Split::Alternative)
alternative
else
@experiment.alternatives.find { |a| a.name == alternative }
end
end
def complete!(context = nil)
if alternative
if Array(goals).empty?
alternative.increment_completion
else
Array(goals).each { |g| alternative.increment_completion(g) }
end
run_callback context, Split.configuration.on_trial_complete
end
end
# Choose an alternative, add a participant, and save the alternative choice on the user. This
# method is guaranteed to only run once, and will skip the alternative choosing process if run
# a second time.
def choose!(context = nil)
@user.cleanup_old_experiments!
# Only run the process once
return alternative if @alternative_chosen
new_participant = @user[@experiment.key].nil?
if override_is_alternative?
self.alternative = @options[:override]
if should_store_alternative? && !@user[@experiment.key]
self.alternative.increment_participation
end
elsif @options[:disabled] || Split.configuration.disabled?
self.alternative = @experiment.control
elsif @experiment.has_winner?
self.alternative = @experiment.winner
else
cleanup_old_versions
if exclude_user?
self.alternative = @experiment.control
else
self.alternative = @user[@experiment.key]
if alternative.nil?
if @experiment.cohorting_disabled?
self.alternative = @experiment.control
else
self.alternative = @experiment.next_alternative
# Increment the number of participants since we are actually choosing a new alternative
self.alternative.increment_participation
run_callback context, Split.configuration.on_trial_choose
end
end
end
end
new_participant_and_cohorting_disabled = new_participant && @experiment.cohorting_disabled?
@user[@experiment.key] = alternative.name unless @experiment.has_winner? || !should_store_alternative? || new_participant_and_cohorting_disabled
@alternative_chosen = true
run_callback context, Split.configuration.on_trial unless @options[:disabled] || Split.configuration.disabled? || new_participant_and_cohorting_disabled
alternative
end
private
def run_callback(context, callback_name)
context.send(callback_name, self) if callback_name && context.respond_to?(callback_name, true)
end
def override_is_alternative?
@experiment.alternatives.map(&:name).include?(@options[:override])
end
def should_store_alternative?
if @options[:override] || @options[:disabled]
Split.configuration.store_override
else
!exclude_user?
end
end
def cleanup_old_versions
if @experiment.version > 0
@user.cleanup_old_versions!(@experiment)
end
end
def exclude_user?
@options[:exclude] || @experiment.start_time.nil? || @user.max_experiments_reached?(@experiment.key)
end
end
end
<MSG> Replace winner existance checks with has_winner? to be more readable
<DFF> @@ -10,7 +10,7 @@ module Split
end
def alternative
- @alternative ||= if experiment.winner
+ @alternative ||= if experiment.has_winner?
experiment.winner
end
end
| 1 | Replace winner existance checks with has_winner? to be more readable | 1 | .rb | rb | mit | splitrb/split |
10071383 | <NME> jquery.meow.css
<BEF> .meows {
position: fixed;
top: 0;
right: 0;
}
.meow {
margin: 20px 20px 0 0;
position: relative;
}
.meow .inner {
background: #191919;
zoom: 1;
filter: alpha(opacity = 75);
background: rgba(25, 25, 25, .75);
border: 2px solid transparent;
-moz-border-radius: 10px;
-webket-border-radius: 10px;
-khtml-border-radius: 10px;
-o-border-radius: 10px;
border-radius: 10px;
-moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
-webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
-khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
-o-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
color: #fff;
font-family: Helvetica, Arial, sans-serif;
font-size: 15px;
padding: 10px;
text-shadow: 1px 1px 3px #000;
width: 300px;
min-height: 48px;
}
.meow .inner:after {
content: "\0200";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.meow.hover .inner {
border: 2px solid #fff;
}
.meow .inner h1 {
font-size: 14px;
font-weight: bold;
margin: 0;
padding: 0;
line-height: 1;
}
.meow .inner .icon {
width: 48px;
height: 48px;
float: left;
margin-right: 6px;
}
.meow .inner .icon img {
max-width: 48px;
max-height: 48px;
}
.meow .inner .close {
display: none;
}
.meow.hover .inner .close {
background: #191919;
zoom: 1;
filter: alpha(opacity = 75);
background: rgba(25, 25, 25, .75);
border: 2px solid #ffffff;
-khtml-border-radius: 18px;
-moz-border-radius: 18px;
-o-border-radius: 18px;
-webket-border-radius: 18px;
border-radius: 18px;
color: #ffffff;
display: block;
font-size: 22px;
font-weight: 500;
height: 18px;
left: 4px;
line-height: 14px;
position: absolute;
text-align: center;
text-decoration: none;
top: 4px;
width: 18px;
}
<MSG> Merge pull request #12 from shpoonj/master
square nyan-cat, stable cross browser support, tidy css
<DFF> @@ -3,86 +3,106 @@
top: 0;
right: 0;
}
+
.meow {
- margin: 20px 20px 0 0;
position: relative;
+ margin: 20px 20px 0 0;
}
+
.meow .inner {
- background: #191919;
- zoom: 1;
- filter: alpha(opacity = 75);
- background: rgba(25, 25, 25, .75);
- border: 2px solid transparent;
- -moz-border-radius: 10px;
- -webket-border-radius: 10px;
- -khtml-border-radius: 10px;
- -o-border-radius: 10px;
- border-radius: 10px;
- -moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
- -webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
- -khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
- -o-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
- box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
- color: #fff;
+ width: 300px;
+ min-height: 48px;
+ padding: 10px;
font-family: Helvetica, Arial, sans-serif;
font-size: 15px;
- padding: 10px;
+ color: #fff;
text-shadow: 1px 1px 3px #000;
- width: 300px;
- min-height: 48px;
+ background: #191919;
+ border: 2px solid transparent;
+ -webkit-border-radius: 10px;
+ -khtml-border-radius: 10px;
+ -moz-border-radius: 10px;
+ -ms-border-radius: 10px;
+ -o-border-radius: 10px;
+ border-radius: 10px;
+ -webkit-opacity: 0.75;
+ -khtml-opacity: 0.75;
+ -moz-opacity: 0.75;
+ -ms-opacity: 0.75;
+ -o-opacity: 0.75;
+ opacity: 0.75;
+ zoom: 1;
+ -webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
+ -khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
+ -moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
+ -ms-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
+ -o-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
+ box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
}
+
.meow .inner:after {
- content: "\0200";
display: block;
+ height: 0;
clear: both;
- visibility: hidden;
line-height: 0;
- height: 0;
+ content: "\0200";
+ visibility: hidden;
}
+
.meow.hover .inner {
border: 2px solid #fff;
}
+
.meow .inner h1 {
+ padding: 0;
+ margin: 0;
font-size: 14px;
font-weight: bold;
- margin: 0;
- padding: 0;
line-height: 1;
}
+
.meow .inner .icon {
+ float: left;
width: 48px;
height: 48px;
- float: left;
margin-right: 6px;
}
+
.meow .inner .icon img {
max-width: 48px;
max-height: 48px;
}
+
.meow .inner .close {
display: none;
}
+
.meow.hover .inner .close {
- background: #191919;
- zoom: 1;
- filter: alpha(opacity = 75);
- background: rgba(25, 25, 25, .75);
- border: 2px solid #ffffff;
- -khtml-border-radius: 18px;
- -moz-border-radius: 18px;
- -o-border-radius: 18px;
- -webket-border-radius: 18px;
- border-radius: 18px;
- color: #ffffff;
+ position: absolute;
+ top: 4px;
+ left: 4px;
display: block;
+ width: 18px;
+ height: 18px;
font-size: 22px;
font-weight: 500;
- height: 18px;
- left: 4px;
line-height: 14px;
- position: absolute;
+ color: #ffffff;
text-align: center;
text-decoration: none;
- top: 4px;
- width: 18px;
+ background: #191919;
+ border: 2px solid #ffffff;
+ -webkit-border-radius: 18px;
+ -khtml-border-radius: 18px;
+ -moz-border-radius: 18px;
+ -ms-border-radius: 18px;
+ -o-border-radius: 18px;
+ border-radius: 18px;
+ -webkit-opacity: 0.75;
+ -khtml-opacity: 0.75;
+ -moz-opacity: 0.75;
+ -ms-opacity: 0.75;
+ -o-opacity: 0.75;
+ opacity: 0.75;
+ zoom: 1;
}
| 62 | Merge pull request #12 from shpoonj/master | 42 | .css | meow | mit | zacstewart/Meow |
10071384 | <NME> jquery.meow.css
<BEF> .meows {
position: fixed;
top: 0;
right: 0;
}
.meow {
margin: 20px 20px 0 0;
position: relative;
}
.meow .inner {
background: #191919;
zoom: 1;
filter: alpha(opacity = 75);
background: rgba(25, 25, 25, .75);
border: 2px solid transparent;
-moz-border-radius: 10px;
-webket-border-radius: 10px;
-khtml-border-radius: 10px;
-o-border-radius: 10px;
border-radius: 10px;
-moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
-webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
-khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
-o-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
color: #fff;
font-family: Helvetica, Arial, sans-serif;
font-size: 15px;
padding: 10px;
text-shadow: 1px 1px 3px #000;
width: 300px;
min-height: 48px;
}
.meow .inner:after {
content: "\0200";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.meow.hover .inner {
border: 2px solid #fff;
}
.meow .inner h1 {
font-size: 14px;
font-weight: bold;
margin: 0;
padding: 0;
line-height: 1;
}
.meow .inner .icon {
width: 48px;
height: 48px;
float: left;
margin-right: 6px;
}
.meow .inner .icon img {
max-width: 48px;
max-height: 48px;
}
.meow .inner .close {
display: none;
}
.meow.hover .inner .close {
background: #191919;
zoom: 1;
filter: alpha(opacity = 75);
background: rgba(25, 25, 25, .75);
border: 2px solid #ffffff;
-khtml-border-radius: 18px;
-moz-border-radius: 18px;
-o-border-radius: 18px;
-webket-border-radius: 18px;
border-radius: 18px;
color: #ffffff;
display: block;
font-size: 22px;
font-weight: 500;
height: 18px;
left: 4px;
line-height: 14px;
position: absolute;
text-align: center;
text-decoration: none;
top: 4px;
width: 18px;
}
<MSG> Merge pull request #12 from shpoonj/master
square nyan-cat, stable cross browser support, tidy css
<DFF> @@ -3,86 +3,106 @@
top: 0;
right: 0;
}
+
.meow {
- margin: 20px 20px 0 0;
position: relative;
+ margin: 20px 20px 0 0;
}
+
.meow .inner {
- background: #191919;
- zoom: 1;
- filter: alpha(opacity = 75);
- background: rgba(25, 25, 25, .75);
- border: 2px solid transparent;
- -moz-border-radius: 10px;
- -webket-border-radius: 10px;
- -khtml-border-radius: 10px;
- -o-border-radius: 10px;
- border-radius: 10px;
- -moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
- -webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
- -khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
- -o-box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
- box-shadow: 2px 2px 10px rgba(25, 25, 25, .25);
- color: #fff;
+ width: 300px;
+ min-height: 48px;
+ padding: 10px;
font-family: Helvetica, Arial, sans-serif;
font-size: 15px;
- padding: 10px;
+ color: #fff;
text-shadow: 1px 1px 3px #000;
- width: 300px;
- min-height: 48px;
+ background: #191919;
+ border: 2px solid transparent;
+ -webkit-border-radius: 10px;
+ -khtml-border-radius: 10px;
+ -moz-border-radius: 10px;
+ -ms-border-radius: 10px;
+ -o-border-radius: 10px;
+ border-radius: 10px;
+ -webkit-opacity: 0.75;
+ -khtml-opacity: 0.75;
+ -moz-opacity: 0.75;
+ -ms-opacity: 0.75;
+ -o-opacity: 0.75;
+ opacity: 0.75;
+ zoom: 1;
+ -webkit-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
+ -khtml-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
+ -moz-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
+ -ms-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
+ -o-box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
+ box-shadow: 2px 2px 10px rgba(25, 25, 25, 0.25);
}
+
.meow .inner:after {
- content: "\0200";
display: block;
+ height: 0;
clear: both;
- visibility: hidden;
line-height: 0;
- height: 0;
+ content: "\0200";
+ visibility: hidden;
}
+
.meow.hover .inner {
border: 2px solid #fff;
}
+
.meow .inner h1 {
+ padding: 0;
+ margin: 0;
font-size: 14px;
font-weight: bold;
- margin: 0;
- padding: 0;
line-height: 1;
}
+
.meow .inner .icon {
+ float: left;
width: 48px;
height: 48px;
- float: left;
margin-right: 6px;
}
+
.meow .inner .icon img {
max-width: 48px;
max-height: 48px;
}
+
.meow .inner .close {
display: none;
}
+
.meow.hover .inner .close {
- background: #191919;
- zoom: 1;
- filter: alpha(opacity = 75);
- background: rgba(25, 25, 25, .75);
- border: 2px solid #ffffff;
- -khtml-border-radius: 18px;
- -moz-border-radius: 18px;
- -o-border-radius: 18px;
- -webket-border-radius: 18px;
- border-radius: 18px;
- color: #ffffff;
+ position: absolute;
+ top: 4px;
+ left: 4px;
display: block;
+ width: 18px;
+ height: 18px;
font-size: 22px;
font-weight: 500;
- height: 18px;
- left: 4px;
line-height: 14px;
- position: absolute;
+ color: #ffffff;
text-align: center;
text-decoration: none;
- top: 4px;
- width: 18px;
+ background: #191919;
+ border: 2px solid #ffffff;
+ -webkit-border-radius: 18px;
+ -khtml-border-radius: 18px;
+ -moz-border-radius: 18px;
+ -ms-border-radius: 18px;
+ -o-border-radius: 18px;
+ border-radius: 18px;
+ -webkit-opacity: 0.75;
+ -khtml-opacity: 0.75;
+ -moz-opacity: 0.75;
+ -ms-opacity: 0.75;
+ -o-opacity: 0.75;
+ opacity: 0.75;
+ zoom: 1;
}
| 62 | Merge pull request #12 from shpoonj/master | 42 | .css | meow | mit | zacstewart/Meow |
10071385 | <NME> convert.ts
<BEF> import { equal } from 'assert';
import parser, { ParserOptions } from '../src';
import stringify from './assets/stringify-node';
function parse(abbr: string, options?: ParserOptions) {
return stringify(parser(abbr, options));
}
describe('Convert token abbreviations', () => {
it('basic', () => {
equal(parse('ul>li.item$*3'), '<ul><li class="item1"></li><li class="item2"></li><li class="item3"></li></ul>');
equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li class="item1">foo$</li><li class="item2">bar$</li></ul>');
equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li class="foo$">item 1</li><li class="bar$">item 2</li></ul>');
equal(parse('ul>li.item$*'), '<ul><li class="item1"></li></ul>');
equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li class="item1">foo.bar</li><li class="item2">hello.world</li></ul>');
});
it('unroll', () => {
equal(parse('p{hi}', { text: ['hello'] }), '<p>hihello</p>');
equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>');
equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>');
equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>');
equal(parse('a>(((b>c))*4)+d'), '<a><b><c></c></b><b><c></c></b><b><c></c></b><b><c></c></b><d></d></a>');
equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt></dt><dd></dd><dt></dt><dd></dd></dl></div>');
equal(parse('a*2>b*3'), '<a><b></b><b></b><b></b></a><a><b></b><b></b><b></b></a>');
equal(parse('a>(b+c)*2'), '<a><b></b><c></c><b></b><c></c></a>');
equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b></b><c></c><b></b><c></c><d></d><e></e><d></d><e></e></a>');
});
});
equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>');
equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>');
equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>');
equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>');
equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>');
equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>');
equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>');
equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>');
// Should move `<div>` as sibling of `{foo}`
equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>');
equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>');
});
it('limit unroll', () => {
// Limit amount of repeated elements
equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>');
equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>');
equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>');
});
it('parent repeater', () => {
equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>');
equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>');
});
it('href', () => {
equal(parse('a', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>');
equal(parse('a', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>');
equal(parse('a', { href: true, text: 'google.it' }), '<a href="">google.it</a>');
equal(parse('a', { href: true, text: 'test here' }), '<a href="">test here</a>');
equal(parse('a', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>');
equal(parse('a', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>');
equal(parse('a', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>');
equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>');
equal(parse('a[href=]', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>');
equal(parse('a[href=]', { href: true, text: 'google.it' }), '<a href="">google.it</a>');
equal(parse('a[href=]', { href: true, text: 'test here' }), '<a href="">test here</a>');
equal(parse('a[href=]', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>');
equal(parse('a[href=]', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>');
equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>');
equal(parse('a[class=here]', { href: true, text: '[email protected]' }), '<a class="here", href="mailto:[email protected]">[email protected]</a>');
equal(parse('a.here', { href: true, text: 'www.domain.com' }), '<a class="here", href="http://www.domain.com">www.domain.com</a>');
equal(parse('a[class=here]', { href: true, text: 'test here [email protected]' }), '<a class="here", href="">test here [email protected]</a>');
equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), '<a class="here", href="">test here www.domain.com</a>');
equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>');
equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>');
});
it('wrap basic', () => {
equal(parse('p', { text: 'test' }), '<p>test</p>');
equal(parse('p', { text: ['test'] }), '<p>test</p>');
equal(parse('p', { text: ['test1', 'test2'] }), '<p>test1\ntest2</p>');
equal(parse('p', { text: ['test1', '', 'test2'] }), '<p>test1\n\ntest2</p>');
equal(parse('p*', { text: ['test1', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>');
equal(parse('p*', { text: ['test1', '', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>');
})
});
<MSG> Attach repeater to unrolled group content
<DFF> @@ -8,11 +8,11 @@ function parse(abbr: string, options?: ParserOptions) {
describe('Convert token abbreviations', () => {
it('basic', () => {
- equal(parse('ul>li.item$*3'), '<ul><li class="item1"></li><li class="item2"></li><li class="item3"></li></ul>');
- equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li class="item1">foo$</li><li class="item2">bar$</li></ul>');
- equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li class="foo$">item 1</li><li class="bar$">item 2</li></ul>');
- equal(parse('ul>li.item$*'), '<ul><li class="item1"></li></ul>');
- equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li class="item1">foo.bar</li><li class="item2">hello.world</li></ul>');
+ equal(parse('ul>li.item$*3'), '<ul><li*3@0 class="item1"></li><li*3@1 class="item2"></li><li*3@2 class="item3"></li></ul>');
+ equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="item1">foo$</li><li*2@1 class="item2">bar$</li></ul>');
+ equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="foo$">item 1</li><li*2@1 class="bar$">item 2</li></ul>');
+ equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>');
+ equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>');
});
it('unroll', () => {
@@ -20,11 +20,11 @@ describe('Convert token abbreviations', () => {
equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>');
equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>');
equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>');
- equal(parse('a>(((b>c))*4)+d'), '<a><b><c></c></b><b><c></c></b><b><c></c></b><b><c></c></b><d></d></a>');
- equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt></dt><dd></dd><dt></dt><dd></dd></dl></div>');
+ equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>');
+ equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>');
- equal(parse('a*2>b*3'), '<a><b></b><b></b><b></b></a><a><b></b><b></b><b></b></a>');
- equal(parse('a>(b+c)*2'), '<a><b></b><c></c><b></b><c></c></a>');
- equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b></b><c></c><b></b><c></c><d></d><e></e><d></d><e></e></a>');
+ equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>');
+ equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>');
+ equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>');
});
});
| 10 | Attach repeater to unrolled group content | 10 | .ts | ts | mit | emmetio/emmet |
10071386 | <NME> convert.ts
<BEF> import { equal } from 'assert';
import parser, { ParserOptions } from '../src';
import stringify from './assets/stringify-node';
function parse(abbr: string, options?: ParserOptions) {
return stringify(parser(abbr, options));
}
describe('Convert token abbreviations', () => {
it('basic', () => {
equal(parse('ul>li.item$*3'), '<ul><li class="item1"></li><li class="item2"></li><li class="item3"></li></ul>');
equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li class="item1">foo$</li><li class="item2">bar$</li></ul>');
equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li class="foo$">item 1</li><li class="bar$">item 2</li></ul>');
equal(parse('ul>li.item$*'), '<ul><li class="item1"></li></ul>');
equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li class="item1">foo.bar</li><li class="item2">hello.world</li></ul>');
});
it('unroll', () => {
equal(parse('p{hi}', { text: ['hello'] }), '<p>hihello</p>');
equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>');
equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>');
equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>');
equal(parse('a>(((b>c))*4)+d'), '<a><b><c></c></b><b><c></c></b><b><c></c></b><b><c></c></b><d></d></a>');
equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt></dt><dd></dd><dt></dt><dd></dd></dl></div>');
equal(parse('a*2>b*3'), '<a><b></b><b></b><b></b></a><a><b></b><b></b><b></b></a>');
equal(parse('a>(b+c)*2'), '<a><b></b><c></c><b></b><c></c></a>');
equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b></b><c></c><b></b><c></c><d></d><e></e><d></d><e></e></a>');
});
});
equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>');
equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>');
equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>');
equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>');
equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>');
equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>');
equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>');
equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>');
// Should move `<div>` as sibling of `{foo}`
equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>');
equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>');
});
it('limit unroll', () => {
// Limit amount of repeated elements
equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>');
equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>');
equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>');
});
it('parent repeater', () => {
equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>');
equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>');
});
it('href', () => {
equal(parse('a', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>');
equal(parse('a', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>');
equal(parse('a', { href: true, text: 'google.it' }), '<a href="">google.it</a>');
equal(parse('a', { href: true, text: 'test here' }), '<a href="">test here</a>');
equal(parse('a', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>');
equal(parse('a', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>');
equal(parse('a', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>');
equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>');
equal(parse('a[href=]', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>');
equal(parse('a[href=]', { href: true, text: 'google.it' }), '<a href="">google.it</a>');
equal(parse('a[href=]', { href: true, text: 'test here' }), '<a href="">test here</a>');
equal(parse('a[href=]', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>');
equal(parse('a[href=]', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>');
equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>');
equal(parse('a[class=here]', { href: true, text: '[email protected]' }), '<a class="here", href="mailto:[email protected]">[email protected]</a>');
equal(parse('a.here', { href: true, text: 'www.domain.com' }), '<a class="here", href="http://www.domain.com">www.domain.com</a>');
equal(parse('a[class=here]', { href: true, text: 'test here [email protected]' }), '<a class="here", href="">test here [email protected]</a>');
equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), '<a class="here", href="">test here www.domain.com</a>');
equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>');
equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>');
});
it('wrap basic', () => {
equal(parse('p', { text: 'test' }), '<p>test</p>');
equal(parse('p', { text: ['test'] }), '<p>test</p>');
equal(parse('p', { text: ['test1', 'test2'] }), '<p>test1\ntest2</p>');
equal(parse('p', { text: ['test1', '', 'test2'] }), '<p>test1\n\ntest2</p>');
equal(parse('p*', { text: ['test1', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>');
equal(parse('p*', { text: ['test1', '', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>');
})
});
<MSG> Attach repeater to unrolled group content
<DFF> @@ -8,11 +8,11 @@ function parse(abbr: string, options?: ParserOptions) {
describe('Convert token abbreviations', () => {
it('basic', () => {
- equal(parse('ul>li.item$*3'), '<ul><li class="item1"></li><li class="item2"></li><li class="item3"></li></ul>');
- equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li class="item1">foo$</li><li class="item2">bar$</li></ul>');
- equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li class="foo$">item 1</li><li class="bar$">item 2</li></ul>');
- equal(parse('ul>li.item$*'), '<ul><li class="item1"></li></ul>');
- equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li class="item1">foo.bar</li><li class="item2">hello.world</li></ul>');
+ equal(parse('ul>li.item$*3'), '<ul><li*3@0 class="item1"></li><li*3@1 class="item2"></li><li*3@2 class="item3"></li></ul>');
+ equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="item1">foo$</li><li*2@1 class="item2">bar$</li></ul>');
+ equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="foo$">item 1</li><li*2@1 class="bar$">item 2</li></ul>');
+ equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>');
+ equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>');
});
it('unroll', () => {
@@ -20,11 +20,11 @@ describe('Convert token abbreviations', () => {
equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>');
equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>');
equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>');
- equal(parse('a>(((b>c))*4)+d'), '<a><b><c></c></b><b><c></c></b><b><c></c></b><b><c></c></b><d></d></a>');
- equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt></dt><dd></dd><dt></dt><dd></dd></dl></div>');
+ equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>');
+ equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>');
- equal(parse('a*2>b*3'), '<a><b></b><b></b><b></b></a><a><b></b><b></b><b></b></a>');
- equal(parse('a>(b+c)*2'), '<a><b></b><c></c><b></b><c></c></a>');
- equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b></b><c></c><b></b><c></c><d></d><e></e><d></d><e></e></a>');
+ equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>');
+ equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>');
+ equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>');
});
});
| 10 | Attach repeater to unrolled group content | 10 | .ts | ts | mit | emmetio/emmet |
10071387 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
end
describe 'finished' do
it 'should increment the counter for the completed alternative' do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
finished('link_color')
new_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
new_completion_count.should eql(previous_completion_count + 1)
end
it "should clear out the user's participation from their session" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql("link_color" => alternative_name)
finished('link_color')
session[:split].should == {}
end
it "should not clear out the users session if reset is false" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql("link_color" => alternative_name)
finished('link_color', :reset => false)
session[:split].should eql("link_color" => alternative_name)
end
it "should reset the users session when experiment is not versioned" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql(experiment.key => alternative_name)
finished('link_color', :reset => true)
session[:split].should eql({})
end
it "should reset the users session when experiment is versioned" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
experiment.increment_version
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql(experiment.key => alternative_name)
finished('link_color', :reset => true)
session[:split].should eql({})
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #78 from dimko/master
Do not increment the experiment's counter if reset is false and user has already finished it
<DFF> @@ -99,61 +99,55 @@ describe Split::Helper do
end
describe 'finished' do
- it 'should increment the counter for the completed alternative' do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
+ before(:each) do
+ @experiment_name = 'link_color'
+ @alternatives = ['blue', 'red']
+ @experiment = Split::Experiment.find_or_create(@experiment_name, *@alternatives)
+ @alternative_name = ab_test(@experiment_name, *@alternatives)
+ @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
+ end
- finished('link_color')
+ it 'should increment the counter for the completed alternative' do
+ finished(@experiment_name)
+ new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
+ new_completion_count.should eql(@previous_completion_count + 1)
+ end
- new_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
+ it "should set experiment's finished key if reset is false" do
+ finished(@experiment_name, :reset => false)
+ session[:split].should eql(@experiment.key => @alternative_name, @experiment.finished_key => true)
+ end
- new_completion_count.should eql(previous_completion_count + 1)
+ it 'should not increment the counter if reset is false and the experiment has been already finished' do
+ 2.times { finished(@experiment_name, :reset => false) }
+ new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
+ new_completion_count.should eql(@previous_completion_count + 1)
end
it "should clear out the user's participation from their session" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
-
- session[:split].should eql("link_color" => alternative_name)
- finished('link_color')
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name)
session[:split].should == {}
end
it "should not clear out the users session if reset is false" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
-
- session[:split].should eql("link_color" => alternative_name)
- finished('link_color', :reset => false)
- session[:split].should eql("link_color" => alternative_name)
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name, :reset => false)
+ session[:split].should eql(@experiment.key => @alternative_name, @experiment.finished_key => true)
end
it "should reset the users session when experiment is not versioned" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
-
- session[:split].should eql(experiment.key => alternative_name)
- finished('link_color', :reset => true)
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name)
session[:split].should eql({})
end
it "should reset the users session when experiment is versioned" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- experiment.increment_version
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
+ @experiment.increment_version
+ @alternative_name = ab_test(@experiment_name, *@alternatives)
- session[:split].should eql(experiment.key => alternative_name)
- finished('link_color', :reset => true)
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name)
session[:split].should eql({})
end
| 31 | Merge pull request #78 from dimko/master | 37 | .rb | rb | mit | splitrb/split |
10071388 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
end
describe 'finished' do
it 'should increment the counter for the completed alternative' do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
finished('link_color')
new_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
new_completion_count.should eql(previous_completion_count + 1)
end
it "should clear out the user's participation from their session" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql("link_color" => alternative_name)
finished('link_color')
session[:split].should == {}
end
it "should not clear out the users session if reset is false" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql("link_color" => alternative_name)
finished('link_color', :reset => false)
session[:split].should eql("link_color" => alternative_name)
end
it "should reset the users session when experiment is not versioned" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql(experiment.key => alternative_name)
finished('link_color', :reset => true)
session[:split].should eql({})
end
it "should reset the users session when experiment is versioned" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
experiment.increment_version
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql(experiment.key => alternative_name)
finished('link_color', :reset => true)
session[:split].should eql({})
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #78 from dimko/master
Do not increment the experiment's counter if reset is false and user has already finished it
<DFF> @@ -99,61 +99,55 @@ describe Split::Helper do
end
describe 'finished' do
- it 'should increment the counter for the completed alternative' do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
+ before(:each) do
+ @experiment_name = 'link_color'
+ @alternatives = ['blue', 'red']
+ @experiment = Split::Experiment.find_or_create(@experiment_name, *@alternatives)
+ @alternative_name = ab_test(@experiment_name, *@alternatives)
+ @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
+ end
- finished('link_color')
+ it 'should increment the counter for the completed alternative' do
+ finished(@experiment_name)
+ new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
+ new_completion_count.should eql(@previous_completion_count + 1)
+ end
- new_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
+ it "should set experiment's finished key if reset is false" do
+ finished(@experiment_name, :reset => false)
+ session[:split].should eql(@experiment.key => @alternative_name, @experiment.finished_key => true)
+ end
- new_completion_count.should eql(previous_completion_count + 1)
+ it 'should not increment the counter if reset is false and the experiment has been already finished' do
+ 2.times { finished(@experiment_name, :reset => false) }
+ new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
+ new_completion_count.should eql(@previous_completion_count + 1)
end
it "should clear out the user's participation from their session" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
-
- session[:split].should eql("link_color" => alternative_name)
- finished('link_color')
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name)
session[:split].should == {}
end
it "should not clear out the users session if reset is false" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
-
- session[:split].should eql("link_color" => alternative_name)
- finished('link_color', :reset => false)
- session[:split].should eql("link_color" => alternative_name)
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name, :reset => false)
+ session[:split].should eql(@experiment.key => @alternative_name, @experiment.finished_key => true)
end
it "should reset the users session when experiment is not versioned" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
-
- session[:split].should eql(experiment.key => alternative_name)
- finished('link_color', :reset => true)
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name)
session[:split].should eql({})
end
it "should reset the users session when experiment is versioned" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- experiment.increment_version
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
+ @experiment.increment_version
+ @alternative_name = ab_test(@experiment_name, *@alternatives)
- session[:split].should eql(experiment.key => alternative_name)
- finished('link_color', :reset => true)
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name)
session[:split].should eql({})
end
| 31 | Merge pull request #78 from dimko/master | 37 | .rb | rb | mit | splitrb/split |
10071389 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
end
describe 'finished' do
it 'should increment the counter for the completed alternative' do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
finished('link_color')
new_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
new_completion_count.should eql(previous_completion_count + 1)
end
it "should clear out the user's participation from their session" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql("link_color" => alternative_name)
finished('link_color')
session[:split].should == {}
end
it "should not clear out the users session if reset is false" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql("link_color" => alternative_name)
finished('link_color', :reset => false)
session[:split].should eql("link_color" => alternative_name)
end
it "should reset the users session when experiment is not versioned" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql(experiment.key => alternative_name)
finished('link_color', :reset => true)
session[:split].should eql({})
end
it "should reset the users session when experiment is versioned" do
experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
experiment.increment_version
alternative_name = ab_test('link_color', 'blue', 'red')
previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
session[:split].should eql(experiment.key => alternative_name)
finished('link_color', :reset => true)
session[:split].should eql({})
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #78 from dimko/master
Do not increment the experiment's counter if reset is false and user has already finished it
<DFF> @@ -99,61 +99,55 @@ describe Split::Helper do
end
describe 'finished' do
- it 'should increment the counter for the completed alternative' do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
+ before(:each) do
+ @experiment_name = 'link_color'
+ @alternatives = ['blue', 'red']
+ @experiment = Split::Experiment.find_or_create(@experiment_name, *@alternatives)
+ @alternative_name = ab_test(@experiment_name, *@alternatives)
+ @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
+ end
- finished('link_color')
+ it 'should increment the counter for the completed alternative' do
+ finished(@experiment_name)
+ new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
+ new_completion_count.should eql(@previous_completion_count + 1)
+ end
- new_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
+ it "should set experiment's finished key if reset is false" do
+ finished(@experiment_name, :reset => false)
+ session[:split].should eql(@experiment.key => @alternative_name, @experiment.finished_key => true)
+ end
- new_completion_count.should eql(previous_completion_count + 1)
+ it 'should not increment the counter if reset is false and the experiment has been already finished' do
+ 2.times { finished(@experiment_name, :reset => false) }
+ new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
+ new_completion_count.should eql(@previous_completion_count + 1)
end
it "should clear out the user's participation from their session" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
-
- session[:split].should eql("link_color" => alternative_name)
- finished('link_color')
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name)
session[:split].should == {}
end
it "should not clear out the users session if reset is false" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
-
- session[:split].should eql("link_color" => alternative_name)
- finished('link_color', :reset => false)
- session[:split].should eql("link_color" => alternative_name)
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name, :reset => false)
+ session[:split].should eql(@experiment.key => @alternative_name, @experiment.finished_key => true)
end
it "should reset the users session when experiment is not versioned" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
-
- session[:split].should eql(experiment.key => alternative_name)
- finished('link_color', :reset => true)
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name)
session[:split].should eql({})
end
it "should reset the users session when experiment is versioned" do
- experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
- experiment.increment_version
- alternative_name = ab_test('link_color', 'blue', 'red')
-
- previous_completion_count = Split::Alternative.new(alternative_name, 'link_color').completed_count
+ @experiment.increment_version
+ @alternative_name = ab_test(@experiment_name, *@alternatives)
- session[:split].should eql(experiment.key => alternative_name)
- finished('link_color', :reset => true)
+ session[:split].should eql(@experiment.key => @alternative_name)
+ finished(@experiment_name)
session[:split].should eql({})
end
| 31 | Merge pull request #78 from dimko/master | 37 | .rb | rb | mit | splitrb/split |
10071390 | <NME> index.ts
<BEF> import markupAbbreviation, { Abbreviation } from '@emmetio/abbreviation';
import stylesheetAbbreviation, { CSSAbbreviation } from '@emmetio/css-abbreviation';
import parseMarkup, { stringify as stringifyMarkup } from './markup';
import parseStylesheet, {
stringify as stringifyStylesheet,
convertSnippets as parseStylesheetSnippets,
CSSAbbreviationScope
} from './stylesheet';
import resolveConfig, { UserConfig, Config } from './config';
export default function expandAbbreviation(abbr: string, config?: UserConfig): string {
const resolvedConfig = resolveConfig(config);
return resolvedConfig.type === 'stylesheet'
? stylesheet(abbr, resolvedConfig)
: markup(abbr, resolvedConfig);
}
/**
* Expands given *markup* abbreviation (e.g. regular Emmet abbreviation that
* produces structured output like HTML) and outputs it according to options
* provided in config
*/
export function markup(abbr: string | Abbreviation, config: Config) {
return stringifyMarkup(parseMarkup(abbr, config), config);
}
/**
* Expands given *stylesheet* abbreviation (a special Emmet abbreviation designed for
* stylesheet languages like CSS, SASS etc.) and outputs it according to options
* provided in config
*/
export function stylesheet(abbr: string | CSSAbbreviation, config: Config) {
return stringifyStylesheet(parseStylesheet(abbr, config), config);
}
export {
markupAbbreviation, parseMarkup, stringifyMarkup,
stylesheetAbbreviation, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets
};
export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation';
export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config';
export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation';
export { GlobalConfig, SyntaxType, Config, UserConfig, Options, AbbreviationContext, default as resolveConfig } from './config';
<MSG> Export more interfaces
<DFF> @@ -38,4 +38,4 @@ export {
stylesheetAbbreviation, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets
};
export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation';
-export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config';
+export { GlobalConfig, SyntaxType, Config, UserConfig, Options, AbbreviationContext, default as resolveConfig } from './config';
| 1 | Export more interfaces | 1 | .ts | ts | mit | emmetio/emmet |
10071391 | <NME> index.ts
<BEF> import markupAbbreviation, { Abbreviation } from '@emmetio/abbreviation';
import stylesheetAbbreviation, { CSSAbbreviation } from '@emmetio/css-abbreviation';
import parseMarkup, { stringify as stringifyMarkup } from './markup';
import parseStylesheet, {
stringify as stringifyStylesheet,
convertSnippets as parseStylesheetSnippets,
CSSAbbreviationScope
} from './stylesheet';
import resolveConfig, { UserConfig, Config } from './config';
export default function expandAbbreviation(abbr: string, config?: UserConfig): string {
const resolvedConfig = resolveConfig(config);
return resolvedConfig.type === 'stylesheet'
? stylesheet(abbr, resolvedConfig)
: markup(abbr, resolvedConfig);
}
/**
* Expands given *markup* abbreviation (e.g. regular Emmet abbreviation that
* produces structured output like HTML) and outputs it according to options
* provided in config
*/
export function markup(abbr: string | Abbreviation, config: Config) {
return stringifyMarkup(parseMarkup(abbr, config), config);
}
/**
* Expands given *stylesheet* abbreviation (a special Emmet abbreviation designed for
* stylesheet languages like CSS, SASS etc.) and outputs it according to options
* provided in config
*/
export function stylesheet(abbr: string | CSSAbbreviation, config: Config) {
return stringifyStylesheet(parseStylesheet(abbr, config), config);
}
export {
markupAbbreviation, parseMarkup, stringifyMarkup,
stylesheetAbbreviation, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets
};
export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation';
export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config';
export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation';
export { GlobalConfig, SyntaxType, Config, UserConfig, Options, AbbreviationContext, default as resolveConfig } from './config';
<MSG> Export more interfaces
<DFF> @@ -38,4 +38,4 @@ export {
stylesheetAbbreviation, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets
};
export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation';
-export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config';
+export { GlobalConfig, SyntaxType, Config, UserConfig, Options, AbbreviationContext, default as resolveConfig } from './config';
| 1 | Export more interfaces | 1 | .ts | ts | mit | emmetio/emmet |
10071392 | <NME> alternative.rb
<BEF> # frozen_string_literal: true
module Split
class Alternative
attr_accessor :name
attr_accessor :experiment_name
attr_accessor :weight
attr_accessor :recorded_info
def initialize(name, experiment_name)
@experiment_name = experiment_name
if Hash === name
@name = name.keys.first
@weight = name.values.first
else
@name = name
@weight = 1
end
@p_winner = 0.0
end
def participant_count
Split.redis.hget(key, 'participant_count').to_i
end
def participant_count=(count)
Split.redis.hset(key, 'participant_count', count.to_i)
end
def completed_count
Split.redis.hget(key, 'completed_count').to_i
end
def unfinished_count
field = set_prob_field(goal)
end
def completed_count=(count)
Split.redis.hset(key, 'completed_count', count.to_i)
end
def increment_participation
Split.redis.hincrby key, 'participant_count', 1
end
def increment_completion
Split.redis.hincrby key, 'completed_count', 1
end
def control?
def all_completed_count
if goals.empty?
completed_count
else
goals.inject(completed_count) do |sum, g|
sum + completed_count(g)
end
end
end
def unfinished_count
participant_count - all_completed_count
end
def set_field(goal)
field = "completed_count"
field += ":" + goal unless goal.nil?
field
end
def set_prob_field(goal)
field = "p_winner"
field += ":" + goal unless goal.nil?
field
end
def set_completed_count(count, goal = nil)
field = set_field(goal)
Split.redis.hset(key, field, count.to_i)
end
def increment_participation
Split.redis.hincrby key, "participant_count", 1
end
def increment_completion(goal = nil)
field = set_field(goal)
Split.redis.hincrby(key, field, 1)
end
end
def reset
Split.redis.hmset key, 'participant_count', 0, 'completed_count', 0
end
def experiment
Split::ExperimentCatalog.find(experiment_name)
end
def z_score(goal = nil)
# p_a = Pa = proportion of users who converted within the experiment split (conversion rate)
# p_c = Pc = proportion of users who converted within the control split (conversion rate)
# n_a = Na = the number of impressions within the experiment split
# n_c = Nc = the number of impressions within the control split
control = experiment.control
alternative = self
return "N/A" if control.name == alternative.name
p_a = alternative.conversion_rate(goal)
p_c = control.conversion_rate(goal)
n_a = alternative.participant_count
n_c = control.participant_count
# can't calculate zscore for P(x) > 1
return "N/A" if p_a > 1 || p_c > 1
Split::Zscore.calculate(p_a, n_a, p_c, n_c)
end
def extra_info
data = Split.redis.hget(key, "recorded_info")
if data && data.length > 1
begin
JSON.parse(data)
rescue
{}
end
else
{}
end
end
def record_extra_info(k, value = 1)
@recorded_info = self.extra_info || {}
if value.kind_of?(Numeric)
@recorded_info[k] ||= 0
@recorded_info[k] += value
else
@recorded_info[k] = value
end
Split.redis.hset key, "recorded_info", (@recorded_info || {}).to_json
end
def save
Split.redis.hsetnx key, "participant_count", 0
Split.redis.hsetnx key, "completed_count", 0
Split.redis.hsetnx key, "p_winner", p_winner
Split.redis.hsetnx key, "recorded_info", (@recorded_info || {}).to_json
end
def validate!
unless String === @name || hash_with_correct_values?(@name)
raise ArgumentError, "Alternative must be a string"
end
end
def reset
Split.redis.hmset key, "participant_count", 0, "completed_count", 0, "recorded_info", ""
unless goals.empty?
goals.each do |g|
field = "completed_count:#{g}"
Split.redis.hset key, field, 0
end
end
end
def delete
Split.redis.del(key)
end
private
def hash_with_correct_values?(name)
Hash === name && String === name.keys.first && Float(name.values.first) rescue false
end
def key
"#{experiment_name}:#{name}"
end
end
end
<MSG> memoize for performance.
<DFF> @@ -20,15 +20,16 @@ module Split
end
def participant_count
- Split.redis.hget(key, 'participant_count').to_i
+ @participant_count ||= Split.redis.hget(key, 'participant_count').to_i
end
def participant_count=(count)
+ @participant_count = count
Split.redis.hset(key, 'participant_count', count.to_i)
end
def completed_count
- Split.redis.hget(key, 'completed_count').to_i
+ @completed_count ||= Split.redis.hget(key, 'completed_count').to_i
end
def unfinished_count
@@ -36,15 +37,16 @@ module Split
end
def completed_count=(count)
+ @completed_count = count
Split.redis.hset(key, 'completed_count', count.to_i)
end
def increment_participation
- Split.redis.hincrby key, 'participant_count', 1
+ @participant_count = Split.redis.hincrby key, 'participant_count', 1
end
def increment_completion
- Split.redis.hincrby key, 'completed_count', 1
+ @completed_count = Split.redis.hincrby key, 'completed_count', 1
end
def control?
@@ -91,6 +93,8 @@ module Split
end
def reset
+ @participant_count = nil
+ @completed_count = nil
Split.redis.hmset key, 'participant_count', 0, 'completed_count', 0
end
| 8 | memoize for performance. | 4 | .rb | rb | mit | splitrb/split |
10071393 | <NME> alternative.rb
<BEF> # frozen_string_literal: true
module Split
class Alternative
attr_accessor :name
attr_accessor :experiment_name
attr_accessor :weight
attr_accessor :recorded_info
def initialize(name, experiment_name)
@experiment_name = experiment_name
if Hash === name
@name = name.keys.first
@weight = name.values.first
else
@name = name
@weight = 1
end
@p_winner = 0.0
end
def participant_count
Split.redis.hget(key, 'participant_count').to_i
end
def participant_count=(count)
Split.redis.hset(key, 'participant_count', count.to_i)
end
def completed_count
Split.redis.hget(key, 'completed_count').to_i
end
def unfinished_count
field = set_prob_field(goal)
end
def completed_count=(count)
Split.redis.hset(key, 'completed_count', count.to_i)
end
def increment_participation
Split.redis.hincrby key, 'participant_count', 1
end
def increment_completion
Split.redis.hincrby key, 'completed_count', 1
end
def control?
def all_completed_count
if goals.empty?
completed_count
else
goals.inject(completed_count) do |sum, g|
sum + completed_count(g)
end
end
end
def unfinished_count
participant_count - all_completed_count
end
def set_field(goal)
field = "completed_count"
field += ":" + goal unless goal.nil?
field
end
def set_prob_field(goal)
field = "p_winner"
field += ":" + goal unless goal.nil?
field
end
def set_completed_count(count, goal = nil)
field = set_field(goal)
Split.redis.hset(key, field, count.to_i)
end
def increment_participation
Split.redis.hincrby key, "participant_count", 1
end
def increment_completion(goal = nil)
field = set_field(goal)
Split.redis.hincrby(key, field, 1)
end
end
def reset
Split.redis.hmset key, 'participant_count', 0, 'completed_count', 0
end
def experiment
Split::ExperimentCatalog.find(experiment_name)
end
def z_score(goal = nil)
# p_a = Pa = proportion of users who converted within the experiment split (conversion rate)
# p_c = Pc = proportion of users who converted within the control split (conversion rate)
# n_a = Na = the number of impressions within the experiment split
# n_c = Nc = the number of impressions within the control split
control = experiment.control
alternative = self
return "N/A" if control.name == alternative.name
p_a = alternative.conversion_rate(goal)
p_c = control.conversion_rate(goal)
n_a = alternative.participant_count
n_c = control.participant_count
# can't calculate zscore for P(x) > 1
return "N/A" if p_a > 1 || p_c > 1
Split::Zscore.calculate(p_a, n_a, p_c, n_c)
end
def extra_info
data = Split.redis.hget(key, "recorded_info")
if data && data.length > 1
begin
JSON.parse(data)
rescue
{}
end
else
{}
end
end
def record_extra_info(k, value = 1)
@recorded_info = self.extra_info || {}
if value.kind_of?(Numeric)
@recorded_info[k] ||= 0
@recorded_info[k] += value
else
@recorded_info[k] = value
end
Split.redis.hset key, "recorded_info", (@recorded_info || {}).to_json
end
def save
Split.redis.hsetnx key, "participant_count", 0
Split.redis.hsetnx key, "completed_count", 0
Split.redis.hsetnx key, "p_winner", p_winner
Split.redis.hsetnx key, "recorded_info", (@recorded_info || {}).to_json
end
def validate!
unless String === @name || hash_with_correct_values?(@name)
raise ArgumentError, "Alternative must be a string"
end
end
def reset
Split.redis.hmset key, "participant_count", 0, "completed_count", 0, "recorded_info", ""
unless goals.empty?
goals.each do |g|
field = "completed_count:#{g}"
Split.redis.hset key, field, 0
end
end
end
def delete
Split.redis.del(key)
end
private
def hash_with_correct_values?(name)
Hash === name && String === name.keys.first && Float(name.values.first) rescue false
end
def key
"#{experiment_name}:#{name}"
end
end
end
<MSG> memoize for performance.
<DFF> @@ -20,15 +20,16 @@ module Split
end
def participant_count
- Split.redis.hget(key, 'participant_count').to_i
+ @participant_count ||= Split.redis.hget(key, 'participant_count').to_i
end
def participant_count=(count)
+ @participant_count = count
Split.redis.hset(key, 'participant_count', count.to_i)
end
def completed_count
- Split.redis.hget(key, 'completed_count').to_i
+ @completed_count ||= Split.redis.hget(key, 'completed_count').to_i
end
def unfinished_count
@@ -36,15 +37,16 @@ module Split
end
def completed_count=(count)
+ @completed_count = count
Split.redis.hset(key, 'completed_count', count.to_i)
end
def increment_participation
- Split.redis.hincrby key, 'participant_count', 1
+ @participant_count = Split.redis.hincrby key, 'participant_count', 1
end
def increment_completion
- Split.redis.hincrby key, 'completed_count', 1
+ @completed_count = Split.redis.hincrby key, 'completed_count', 1
end
def control?
@@ -91,6 +93,8 @@ module Split
end
def reset
+ @participant_count = nil
+ @completed_count = nil
Split.redis.hmset key, 'participant_count', 0, 'completed_count', 0
end
| 8 | memoize for performance. | 4 | .rb | rb | mit | splitrb/split |
10071394 | <NME> alternative.rb
<BEF> # frozen_string_literal: true
module Split
class Alternative
attr_accessor :name
attr_accessor :experiment_name
attr_accessor :weight
attr_accessor :recorded_info
def initialize(name, experiment_name)
@experiment_name = experiment_name
if Hash === name
@name = name.keys.first
@weight = name.values.first
else
@name = name
@weight = 1
end
@p_winner = 0.0
end
def participant_count
Split.redis.hget(key, 'participant_count').to_i
end
def participant_count=(count)
Split.redis.hset(key, 'participant_count', count.to_i)
end
def completed_count
Split.redis.hget(key, 'completed_count').to_i
end
def unfinished_count
field = set_prob_field(goal)
end
def completed_count=(count)
Split.redis.hset(key, 'completed_count', count.to_i)
end
def increment_participation
Split.redis.hincrby key, 'participant_count', 1
end
def increment_completion
Split.redis.hincrby key, 'completed_count', 1
end
def control?
def all_completed_count
if goals.empty?
completed_count
else
goals.inject(completed_count) do |sum, g|
sum + completed_count(g)
end
end
end
def unfinished_count
participant_count - all_completed_count
end
def set_field(goal)
field = "completed_count"
field += ":" + goal unless goal.nil?
field
end
def set_prob_field(goal)
field = "p_winner"
field += ":" + goal unless goal.nil?
field
end
def set_completed_count(count, goal = nil)
field = set_field(goal)
Split.redis.hset(key, field, count.to_i)
end
def increment_participation
Split.redis.hincrby key, "participant_count", 1
end
def increment_completion(goal = nil)
field = set_field(goal)
Split.redis.hincrby(key, field, 1)
end
end
def reset
Split.redis.hmset key, 'participant_count', 0, 'completed_count', 0
end
def experiment
Split::ExperimentCatalog.find(experiment_name)
end
def z_score(goal = nil)
# p_a = Pa = proportion of users who converted within the experiment split (conversion rate)
# p_c = Pc = proportion of users who converted within the control split (conversion rate)
# n_a = Na = the number of impressions within the experiment split
# n_c = Nc = the number of impressions within the control split
control = experiment.control
alternative = self
return "N/A" if control.name == alternative.name
p_a = alternative.conversion_rate(goal)
p_c = control.conversion_rate(goal)
n_a = alternative.participant_count
n_c = control.participant_count
# can't calculate zscore for P(x) > 1
return "N/A" if p_a > 1 || p_c > 1
Split::Zscore.calculate(p_a, n_a, p_c, n_c)
end
def extra_info
data = Split.redis.hget(key, "recorded_info")
if data && data.length > 1
begin
JSON.parse(data)
rescue
{}
end
else
{}
end
end
def record_extra_info(k, value = 1)
@recorded_info = self.extra_info || {}
if value.kind_of?(Numeric)
@recorded_info[k] ||= 0
@recorded_info[k] += value
else
@recorded_info[k] = value
end
Split.redis.hset key, "recorded_info", (@recorded_info || {}).to_json
end
def save
Split.redis.hsetnx key, "participant_count", 0
Split.redis.hsetnx key, "completed_count", 0
Split.redis.hsetnx key, "p_winner", p_winner
Split.redis.hsetnx key, "recorded_info", (@recorded_info || {}).to_json
end
def validate!
unless String === @name || hash_with_correct_values?(@name)
raise ArgumentError, "Alternative must be a string"
end
end
def reset
Split.redis.hmset key, "participant_count", 0, "completed_count", 0, "recorded_info", ""
unless goals.empty?
goals.each do |g|
field = "completed_count:#{g}"
Split.redis.hset key, field, 0
end
end
end
def delete
Split.redis.del(key)
end
private
def hash_with_correct_values?(name)
Hash === name && String === name.keys.first && Float(name.values.first) rescue false
end
def key
"#{experiment_name}:#{name}"
end
end
end
<MSG> memoize for performance.
<DFF> @@ -20,15 +20,16 @@ module Split
end
def participant_count
- Split.redis.hget(key, 'participant_count').to_i
+ @participant_count ||= Split.redis.hget(key, 'participant_count').to_i
end
def participant_count=(count)
+ @participant_count = count
Split.redis.hset(key, 'participant_count', count.to_i)
end
def completed_count
- Split.redis.hget(key, 'completed_count').to_i
+ @completed_count ||= Split.redis.hget(key, 'completed_count').to_i
end
def unfinished_count
@@ -36,15 +37,16 @@ module Split
end
def completed_count=(count)
+ @completed_count = count
Split.redis.hset(key, 'completed_count', count.to_i)
end
def increment_participation
- Split.redis.hincrby key, 'participant_count', 1
+ @participant_count = Split.redis.hincrby key, 'participant_count', 1
end
def increment_completion
- Split.redis.hincrby key, 'completed_count', 1
+ @completed_count = Split.redis.hincrby key, 'completed_count', 1
end
def control?
@@ -91,6 +93,8 @@ module Split
end
def reset
+ @participant_count = nil
+ @completed_count = nil
Split.redis.hmset key, 'participant_count', 0, 'completed_count', 0
end
| 8 | memoize for performance. | 4 | .rb | rb | mit | splitrb/split |
10071395 | <NME> .rspec
<BEF> ADDFILE
<MSG> Add default rspec configuration to display the slowest specs on the suite
<DFF> @@ -0,0 +1,1 @@
+--profile
\ No newline at end of file
| 1 | Add default rspec configuration to display the slowest specs on the suite | 0 | rspec | mit | splitrb/split |
|
10071396 | <NME> .rspec
<BEF> ADDFILE
<MSG> Add default rspec configuration to display the slowest specs on the suite
<DFF> @@ -0,0 +1,1 @@
+--profile
\ No newline at end of file
| 1 | Add default rspec configuration to display the slowest specs on the suite | 0 | rspec | mit | splitrb/split |
|
10071397 | <NME> .rspec
<BEF> ADDFILE
<MSG> Add default rspec configuration to display the slowest specs on the suite
<DFF> @@ -0,0 +1,1 @@
+--profile
\ No newline at end of file
| 1 | Add default rspec configuration to display the slowest specs on the suite | 0 | rspec | mit | splitrb/split |
|
10071398 | <NME> helper.rb
<BEF> # frozen_string_literal: true
module Split
module Helper
OVERRIDE_PARAM_NAME = "ab_test"
module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives)
alternative = if Split.configuration.enabled && !exclude_visitor?
experiment.save
raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil?
trial = Trial.new(user: ab_user, experiment: experiment,
override: override_alternative(experiment.name), exclude: exclude_visitor?,
disabled: split_generically_disabled?)
alt = trial.choose!(self)
alt ? alt.name : nil
else
control_variable(experiment.control)
end
rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
if Split.configuration.db_failover_allow_parameter_override
alternative = override_alternative(experiment.name) if override_present?(experiment.name)
alternative = control_variable(experiment.control) if split_generically_disabled?
end
ensure
alternative ||= control_variable(experiment.control)
end
if block_given?
metadata = experiment.metadata[alternative] if experiment.metadata
yield(alternative, metadata || {})
else
alternative
end
end
def reset!(experiment)
ab_user.delete(experiment.key)
end
def finish_experiment(experiment, options = { reset: true })
return false if active_experiments[experiment.name].nil?
return true if experiment.has_winner?
should_reset = experiment.resettable? && options[:reset]
if ab_user[experiment.finished_key] && !should_reset
true
else
alternative_name = ab_user[experiment.key]
trial = Trial.new(
user: ab_user,
experiment: experiment,
alternative: alternative_name,
goals: options[:goals],
)
trial.complete!(self)
if should_reset
reset!(experiment)
else
ab_user[experiment.finished_key] = true
end
end
end
def ab_finished(metric_descriptor, options = { reset: true })
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, goals = normalize_metric(metric_descriptor)
end
def finished(metric_descriptor, options = {:reset => true})
warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 1.5.0'
ab_finished(metric_descriptor, options)
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_record_extra_info(metric_descriptor, key, value = 1)
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, _ = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
end
def begin_experiment(experiment, alternative_name = nil)
warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 1.5.0'
alternative_name ||= experiment.control.name
ab_user[experiment.key] = alternative_name
alternative_name
alternative.record_extra_info(key, value) if alternative
end
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_active_experiments
ab_user.active_experiments
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def override_present?(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative_by_params(experiment_name)
defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name]
end
def override_alternative_by_cookies(experiment_name)
return unless defined?(request)
if request.cookies && request.cookies.key?("split_override")
experiments = JSON.parse(request.cookies["split_override"]) rescue {}
experiments[experiment_name]
end
end
def split_generically_disabled?
defined?(params) && params["SPLIT_DISABLE"]
end
def ab_user
@ab_user ||= User.new(self)
end
def exclude_visitor?
defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
defined?(request) && request.user_agent =~ Split.configuration.robot_regex
end
def is_preview?
defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview"
end
def is_ignored_ip_address?
return false if Split.configuration.ignore_ip_addresses.empty?
Split.configuration.ignore_ip_addresses.each do |ip|
return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip))
end
false
end
def active_experiments
ab_user.active_experiments
end
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
goals = Array(metric_descriptor.values.first)
else
experiment_name = metric_descriptor
goals = []
end
return experiment_name, goals
end
def control_variable(control)
Hash === control ? control.keys.first.to_s : control.to_s
end
end
end
<MSG> Deprecated methods will be removed in 2.0.0
<DFF> @@ -75,7 +75,7 @@ module Split
end
def finished(metric_descriptor, options = {:reset => true})
- warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 1.5.0'
+ warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 2.0.0'
ab_finished(metric_descriptor, options)
end
@@ -92,7 +92,7 @@ module Split
end
def begin_experiment(experiment, alternative_name = nil)
- warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 1.5.0'
+ warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 2.0.0'
alternative_name ||= experiment.control.name
ab_user[experiment.key] = alternative_name
alternative_name
| 2 | Deprecated methods will be removed in 2.0.0 | 2 | .rb | rb | mit | splitrb/split |
10071399 | <NME> helper.rb
<BEF> # frozen_string_literal: true
module Split
module Helper
OVERRIDE_PARAM_NAME = "ab_test"
module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives)
alternative = if Split.configuration.enabled && !exclude_visitor?
experiment.save
raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil?
trial = Trial.new(user: ab_user, experiment: experiment,
override: override_alternative(experiment.name), exclude: exclude_visitor?,
disabled: split_generically_disabled?)
alt = trial.choose!(self)
alt ? alt.name : nil
else
control_variable(experiment.control)
end
rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
if Split.configuration.db_failover_allow_parameter_override
alternative = override_alternative(experiment.name) if override_present?(experiment.name)
alternative = control_variable(experiment.control) if split_generically_disabled?
end
ensure
alternative ||= control_variable(experiment.control)
end
if block_given?
metadata = experiment.metadata[alternative] if experiment.metadata
yield(alternative, metadata || {})
else
alternative
end
end
def reset!(experiment)
ab_user.delete(experiment.key)
end
def finish_experiment(experiment, options = { reset: true })
return false if active_experiments[experiment.name].nil?
return true if experiment.has_winner?
should_reset = experiment.resettable? && options[:reset]
if ab_user[experiment.finished_key] && !should_reset
true
else
alternative_name = ab_user[experiment.key]
trial = Trial.new(
user: ab_user,
experiment: experiment,
alternative: alternative_name,
goals: options[:goals],
)
trial.complete!(self)
if should_reset
reset!(experiment)
else
ab_user[experiment.finished_key] = true
end
end
end
def ab_finished(metric_descriptor, options = { reset: true })
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, goals = normalize_metric(metric_descriptor)
end
def finished(metric_descriptor, options = {:reset => true})
warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 1.5.0'
ab_finished(metric_descriptor, options)
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_record_extra_info(metric_descriptor, key, value = 1)
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, _ = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
end
def begin_experiment(experiment, alternative_name = nil)
warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 1.5.0'
alternative_name ||= experiment.control.name
ab_user[experiment.key] = alternative_name
alternative_name
alternative.record_extra_info(key, value) if alternative
end
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_active_experiments
ab_user.active_experiments
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def override_present?(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative_by_params(experiment_name)
defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name]
end
def override_alternative_by_cookies(experiment_name)
return unless defined?(request)
if request.cookies && request.cookies.key?("split_override")
experiments = JSON.parse(request.cookies["split_override"]) rescue {}
experiments[experiment_name]
end
end
def split_generically_disabled?
defined?(params) && params["SPLIT_DISABLE"]
end
def ab_user
@ab_user ||= User.new(self)
end
def exclude_visitor?
defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
defined?(request) && request.user_agent =~ Split.configuration.robot_regex
end
def is_preview?
defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview"
end
def is_ignored_ip_address?
return false if Split.configuration.ignore_ip_addresses.empty?
Split.configuration.ignore_ip_addresses.each do |ip|
return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip))
end
false
end
def active_experiments
ab_user.active_experiments
end
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
goals = Array(metric_descriptor.values.first)
else
experiment_name = metric_descriptor
goals = []
end
return experiment_name, goals
end
def control_variable(control)
Hash === control ? control.keys.first.to_s : control.to_s
end
end
end
<MSG> Deprecated methods will be removed in 2.0.0
<DFF> @@ -75,7 +75,7 @@ module Split
end
def finished(metric_descriptor, options = {:reset => true})
- warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 1.5.0'
+ warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 2.0.0'
ab_finished(metric_descriptor, options)
end
@@ -92,7 +92,7 @@ module Split
end
def begin_experiment(experiment, alternative_name = nil)
- warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 1.5.0'
+ warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 2.0.0'
alternative_name ||= experiment.control.name
ab_user[experiment.key] = alternative_name
alternative_name
| 2 | Deprecated methods will be removed in 2.0.0 | 2 | .rb | rb | mit | splitrb/split |
10071400 | <NME> helper.rb
<BEF> # frozen_string_literal: true
module Split
module Helper
OVERRIDE_PARAM_NAME = "ab_test"
module_function
def ab_test(metric_descriptor, control = nil, *alternatives)
begin
experiment = ExperimentCatalog.find_or_initialize(metric_descriptor, control, *alternatives)
alternative = if Split.configuration.enabled && !exclude_visitor?
experiment.save
raise(Split::InvalidExperimentsFormatError) unless (Split.configuration.experiments || {}).fetch(experiment.name.to_sym, {})[:combined_experiments].nil?
trial = Trial.new(user: ab_user, experiment: experiment,
override: override_alternative(experiment.name), exclude: exclude_visitor?,
disabled: split_generically_disabled?)
alt = trial.choose!(self)
alt ? alt.name : nil
else
control_variable(experiment.control)
end
rescue Errno::ECONNREFUSED, Redis::BaseError, SocketError => e
raise(e) unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
if Split.configuration.db_failover_allow_parameter_override
alternative = override_alternative(experiment.name) if override_present?(experiment.name)
alternative = control_variable(experiment.control) if split_generically_disabled?
end
ensure
alternative ||= control_variable(experiment.control)
end
if block_given?
metadata = experiment.metadata[alternative] if experiment.metadata
yield(alternative, metadata || {})
else
alternative
end
end
def reset!(experiment)
ab_user.delete(experiment.key)
end
def finish_experiment(experiment, options = { reset: true })
return false if active_experiments[experiment.name].nil?
return true if experiment.has_winner?
should_reset = experiment.resettable? && options[:reset]
if ab_user[experiment.finished_key] && !should_reset
true
else
alternative_name = ab_user[experiment.key]
trial = Trial.new(
user: ab_user,
experiment: experiment,
alternative: alternative_name,
goals: options[:goals],
)
trial.complete!(self)
if should_reset
reset!(experiment)
else
ab_user[experiment.finished_key] = true
end
end
end
def ab_finished(metric_descriptor, options = { reset: true })
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, goals = normalize_metric(metric_descriptor)
end
def finished(metric_descriptor, options = {:reset => true})
warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 1.5.0'
ab_finished(metric_descriptor, options)
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_record_extra_info(metric_descriptor, key, value = 1)
return if exclude_visitor? || Split.configuration.disabled?
metric_descriptor, _ = normalize_metric(metric_descriptor)
experiments = Metric.possible_experiments(metric_descriptor)
end
def begin_experiment(experiment, alternative_name = nil)
warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 1.5.0'
alternative_name ||= experiment.control.name
ab_user[experiment.key] = alternative_name
alternative_name
alternative.record_extra_info(key, value) if alternative
end
end
end
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def ab_active_experiments
ab_user.active_experiments
rescue => e
raise unless Split.configuration.db_failover
Split.configuration.db_failover_on_db_error.call(e)
end
def override_present?(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative(experiment_name)
override_alternative_by_params(experiment_name) || override_alternative_by_cookies(experiment_name)
end
def override_alternative_by_params(experiment_name)
defined?(params) && params[OVERRIDE_PARAM_NAME] && params[OVERRIDE_PARAM_NAME][experiment_name]
end
def override_alternative_by_cookies(experiment_name)
return unless defined?(request)
if request.cookies && request.cookies.key?("split_override")
experiments = JSON.parse(request.cookies["split_override"]) rescue {}
experiments[experiment_name]
end
end
def split_generically_disabled?
defined?(params) && params["SPLIT_DISABLE"]
end
def ab_user
@ab_user ||= User.new(self)
end
def exclude_visitor?
defined?(request) && (instance_exec(request, &Split.configuration.ignore_filter) || is_ignored_ip_address? || is_robot? || is_preview?)
end
def is_robot?
defined?(request) && request.user_agent =~ Split.configuration.robot_regex
end
def is_preview?
defined?(request) && defined?(request.headers) && request.headers["x-purpose"] == "preview"
end
def is_ignored_ip_address?
return false if Split.configuration.ignore_ip_addresses.empty?
Split.configuration.ignore_ip_addresses.each do |ip|
return true if defined?(request) && (request.ip == ip || (ip.class == Regexp && request.ip =~ ip))
end
false
end
def active_experiments
ab_user.active_experiments
end
def normalize_metric(metric_descriptor)
if Hash === metric_descriptor
experiment_name = metric_descriptor.keys.first
goals = Array(metric_descriptor.values.first)
else
experiment_name = metric_descriptor
goals = []
end
return experiment_name, goals
end
def control_variable(control)
Hash === control ? control.keys.first.to_s : control.to_s
end
end
end
<MSG> Deprecated methods will be removed in 2.0.0
<DFF> @@ -75,7 +75,7 @@ module Split
end
def finished(metric_descriptor, options = {:reset => true})
- warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 1.5.0'
+ warn 'DEPRECATION WARNING: finished method was renamed to ab_finished and will be removed in Split 2.0.0'
ab_finished(metric_descriptor, options)
end
@@ -92,7 +92,7 @@ module Split
end
def begin_experiment(experiment, alternative_name = nil)
- warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 1.5.0'
+ warn 'DEPRECATION WARNING: begin_experiment is deprecated and will be removed from Split 2.0.0'
alternative_name ||= experiment.control.name
ab_user[experiment.key] = alternative_name
alternative_name
| 2 | Deprecated methods will be removed in 2.0.0 | 2 | .rb | rb | mit | splitrb/split |
10071401 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
end
describe 'persistent configuration' do
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Respect experiment defaults when loading experiments in initializer.
<DFF> @@ -118,6 +118,23 @@ describe Split::Experiment do
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
+
+ context 'from configuration' do
+ let(:experiment_name) { :my_experiment }
+ let(:experiments) do
+ {
+ experiment_name => {
+ :alternatives => ['Control Opt', 'Alt one']
+ }
+ }
+ end
+
+ before { Split.configuration.experiments = experiments }
+
+ it 'assigns default values to the experiment' do
+ expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
+ end
+ end
end
describe 'persistent configuration' do
| 17 | Respect experiment defaults when loading experiments in initializer. | 0 | .rb | rb | mit | splitrb/split |
10071402 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
end
describe 'persistent configuration' do
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Respect experiment defaults when loading experiments in initializer.
<DFF> @@ -118,6 +118,23 @@ describe Split::Experiment do
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
+
+ context 'from configuration' do
+ let(:experiment_name) { :my_experiment }
+ let(:experiments) do
+ {
+ experiment_name => {
+ :alternatives => ['Control Opt', 'Alt one']
+ }
+ }
+ end
+
+ before { Split.configuration.experiments = experiments }
+
+ it 'assigns default values to the experiment' do
+ expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
+ end
+ end
end
describe 'persistent configuration' do
| 17 | Respect experiment defaults when loading experiments in initializer. | 0 | .rb | rb | mit | splitrb/split |
10071403 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
end
describe 'persistent configuration' do
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
end
it "should persist algorithm in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should persist a new experiment in redis, that does not exist in the configuration file" do
experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash)
experiment.save
e = Split::ExperimentCatalog.find("foobar")
expect(e).to eq(experiment)
expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"])
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Respect experiment defaults when loading experiments in initializer.
<DFF> @@ -118,6 +118,23 @@ describe Split::Experiment do
experiment = Split::Experiment.new('basket_text', :alternatives => ['Basket', "Cart"], :resettable => false)
expect(experiment.resettable).to be_falsey
end
+
+ context 'from configuration' do
+ let(:experiment_name) { :my_experiment }
+ let(:experiments) do
+ {
+ experiment_name => {
+ :alternatives => ['Control Opt', 'Alt one']
+ }
+ }
+ end
+
+ before { Split.configuration.experiments = experiments }
+
+ it 'assigns default values to the experiment' do
+ expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
+ end
+ end
end
describe 'persistent configuration' do
| 17 | Respect experiment defaults when loading experiments in initializer. | 0 | .rb | rb | mit | splitrb/split |
10071404 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should be possible to make an experiment not resettable" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
expect(experiment.resettable).to be_falsey
end
context "from configuration" do
let(:experiment_name) { :my_experiment }
let(:experiments) do
{
experiment_name => {
alternatives: ["Control Opt", "Alt one"]
}
}
end
before { Split.configuration.experiments = experiments }
it "assigns default values to the experiment" do
expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
end
end
end
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
lambda { Split::Experiment.find_or_create('link_enabled', true, false) }.should raise_error
end
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Merge pull request #40 from andreas/master
Fix specifying weights for existing experiments
<DFF> @@ -184,4 +184,20 @@ describe Split::Experiment do
lambda { Split::Experiment.find_or_create('link_enabled', true, false) }.should raise_error
end
end
-end
\ No newline at end of file
+
+ describe 'specifying weights' do
+ it "should work for a new experiment" do
+ experiment = Split::Experiment.find_or_create('link_color', { 'blue' => 1, 'red' => 2 })
+
+ experiment.alternatives.map(&:weight).should == [1, 2]
+ end
+
+ it "should work for an existing experiment" do
+ experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
+ experiment.save
+
+ same_experiment = Split::Experiment.find_or_create('link_color', { 'blue' => 1, 'red' => 2 })
+ same_experiment.alternatives.map(&:weight).should == [1, 2]
+ end
+ end
+end
| 17 | Merge pull request #40 from andreas/master | 1 | .rb | rb | mit | splitrb/split |
10071405 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should be possible to make an experiment not resettable" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
expect(experiment.resettable).to be_falsey
end
context "from configuration" do
let(:experiment_name) { :my_experiment }
let(:experiments) do
{
experiment_name => {
alternatives: ["Control Opt", "Alt one"]
}
}
end
before { Split.configuration.experiments = experiments }
it "assigns default values to the experiment" do
expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
end
end
end
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
lambda { Split::Experiment.find_or_create('link_enabled', true, false) }.should raise_error
end
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Merge pull request #40 from andreas/master
Fix specifying weights for existing experiments
<DFF> @@ -184,4 +184,20 @@ describe Split::Experiment do
lambda { Split::Experiment.find_or_create('link_enabled', true, false) }.should raise_error
end
end
-end
\ No newline at end of file
+
+ describe 'specifying weights' do
+ it "should work for a new experiment" do
+ experiment = Split::Experiment.find_or_create('link_color', { 'blue' => 1, 'red' => 2 })
+
+ experiment.alternatives.map(&:weight).should == [1, 2]
+ end
+
+ it "should work for an existing experiment" do
+ experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
+ experiment.save
+
+ same_experiment = Split::Experiment.find_or_create('link_color', { 'blue' => 1, 'red' => 2 })
+ same_experiment.alternatives.map(&:weight).should == [1, 2]
+ end
+ end
+end
| 17 | Merge pull request #40 from andreas/master | 1 | .rb | rb | mit | splitrb/split |
10071406 | <NME> experiment_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
require "time"
describe Split::Experiment do
def new_experiment(goals = [])
Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals)
end
def alternative(color)
Split::Alternative.new(color, "link_color")
end
let(:experiment) { new_experiment }
let(:blue) { alternative("blue") }
let(:green) { alternative("green") }
context "with an experiment" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) }
it "should have a name" do
expect(experiment.name).to eq("basket_text")
end
it "should have alternatives" do
expect(experiment.alternatives.length).to be 2
end
it "should have alternatives with correct names" do
expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"])
end
it "should be resettable by default" do
expect(experiment.resettable).to be_truthy
end
it "should save to redis" do
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
end
it "should save the start time to redis" do
experiment_start_time = Time.at(1372167761)
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should not save the start time to redis when start_manually is enabled" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should save the selected algorithm to redis" do
experiment_algorithm = Split::Algorithms::Whiplash
experiment.algorithm = experiment_algorithm
experiment.save
expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm)
end
it "should handle having a start time stored as a string" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).twice.and_return(experiment_start_time)
experiment.save
Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time)
end
it "should handle not having a start time" do
experiment_start_time = Time.parse("Sat Mar 03 14:01:03")
expect(Time).to receive(:now).and_return(experiment_start_time)
experiment.save
Split.redis.hdel(:experiment_start_times, experiment.name)
expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil
end
it "should not create duplicates when saving multiple times" do
experiment.save
experiment.save
expect(Split.redis.exists?("basket_text")).to be true
expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}'])
end
describe "new record?" do
it "should know if it hasn't been saved yet" do
expect(experiment.new_record?).to be_truthy
end
it "should know if it has been saved yet" do
experiment.save
expect(experiment.new_record?).to be_falsey
end
end
describe "control" do
it "should be the first alternative" do
experiment.save
expect(experiment.control.name).to eq("Basket")
end
end
end
describe "initialization" do
it "should set the algorithm when passed as an option to the initializer" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash)
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
it "should be possible to make an experiment not resettable" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
expect(experiment.resettable).to be_falsey
end
context "from configuration" do
let(:experiment_name) { :my_experiment }
let(:experiments) do
{
experiment_name => {
alternatives: ["Control Opt", "Alt one"]
}
}
end
before { Split.configuration.experiments = experiments }
it "assigns default values to the experiment" do
expect(Split::Experiment.new(experiment_name).resettable).to eq(true)
end
end
end
describe "persistent configuration" do
it "should persist resettable in redis" do
experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false)
experiment.save
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.resettable).to be_falsey
end
describe "#metadata" do
let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }
let(:meta) { { a: "b" } }
before do
experiment.save
end
it "should delete the key when metadata is removed" do
experiment.metadata = nil
experiment.save
expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey
end
context "simple hash" do
let(:meta) { { "basket" => "a", "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
context "nested hash" do
let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } }
it "should persist metadata in redis" do
e = Split::ExperimentCatalog.find("basket_text")
expect(e).to eq(experiment)
expect(e.metadata).to eq(meta)
end
end
lambda { Split::Experiment.find_or_create('link_enabled', true, false) }.should raise_error
end
end
end
describe "deleting" do
it "should delete itself" do
experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"])
experiment.save
experiment.delete
expect(Split.redis.exists?("link_color")).to be false
expect(Split::ExperimentCatalog.find("link_color")).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.delete
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_delete hook" do
expect(Split.configuration.on_experiment_delete).to receive(:call)
experiment.delete
end
it "should call the on_before_experiment_delete hook" do
expect(Split.configuration.on_before_experiment_delete).to receive(:call)
experiment.delete
end
it "should reset the start time if the experiment should be manually started" do
Split.configuration.start_manually = true
experiment.start
experiment.delete
expect(experiment.start_time).to be_nil
end
it "should default cohorting back to false" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq(true)
experiment.delete
expect(experiment.cohorting_disabled?).to eq(false)
end
end
describe "winner" do
it "should have no winner initially" do
expect(experiment.winner).to be_nil
end
end
describe "winner=" do
it "should allow you to specify a winner" do
experiment.save
experiment.winner = "red"
expect(experiment.winner.name).to eq("red")
end
it "should call the on_experiment_winner_choose hook" do
expect(Split.configuration.on_experiment_winner_choose).to receive(:call)
experiment.winner = "green"
end
context "when has_winner state is memoized" do
before { expect(experiment).to_not have_winner }
it "should keep has_winner state consistent" do
experiment.winner = "red"
expect(experiment).to have_winner
end
end
end
describe "reset_winner" do
before { experiment.winner = "green" }
it "should reset the winner" do
experiment.reset_winner
expect(experiment.winner).to be_nil
end
context "when has_winner state is memoized" do
before { expect(experiment).to have_winner }
it "should keep has_winner state consistent" do
experiment.reset_winner
expect(experiment).to_not have_winner
end
end
end
describe "has_winner?" do
context "with winner" do
before { experiment.winner = "red" }
it "returns true" do
expect(experiment).to have_winner
end
end
context "without winner" do
it "returns false" do
expect(experiment).to_not have_winner
end
end
it "memoizes has_winner state" do
expect(experiment).to receive(:winner).once
expect(experiment).to_not have_winner
expect(experiment).to_not have_winner
end
end
describe "reset" do
let(:reset_manually) { false }
before do
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
experiment.save
green.increment_participation
green.increment_participation
end
it "should reset all alternatives" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
it "should reset the winner" do
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
experiment.reset
expect(experiment.winner).to be_nil
end
it "should increment the version" do
expect(experiment.version).to eq(0)
experiment.reset
expect(experiment.version).to eq(1)
end
it "should call the on_experiment_reset hook" do
expect(Split.configuration.on_experiment_reset).to receive(:call)
experiment.reset
end
it "should call the on_before_experiment_reset hook" do
expect(Split.configuration.on_before_experiment_reset).to receive(:call)
experiment.reset
end
end
describe "algorithm" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
it "should use the default algorithm if none is specified" do
expect(experiment.algorithm).to eq(Split.configuration.algorithm)
end
it "should use the user specified algorithm for this experiment if specified" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)
end
end
describe "#next_alternative" do
context "with multiple alternatives" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") }
context "with winner" do
it "should always return the winner" do
green = Split::Alternative.new("green", "link_color")
experiment.winner = "green"
expect(experiment.next_alternative.name).to eq("green")
green.increment_participation
expect(experiment.next_alternative.name).to eq("green")
end
end
context "without winner" do
it "should use the specified algorithm" do
experiment.algorithm = Split::Algorithms::Whiplash
expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color"))
expect(experiment.next_alternative.name).to eq("green")
end
end
end
context "with single alternative" do
let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") }
it "should always return the only alternative" do
expect(experiment.next_alternative.name).to eq("blue")
expect(experiment.next_alternative.name).to eq("blue")
end
end
end
describe "#cohorting_disabled?" do
it "returns false when nothing has been configured" do
expect(experiment.cohorting_disabled?).to eq false
end
it "returns true when enable_cohorting is performed" do
experiment.enable_cohorting
expect(experiment.cohorting_disabled?).to eq false
end
it "returns false when nothing has been configured" do
experiment.disable_cohorting
expect(experiment.cohorting_disabled?).to eq true
end
end
describe "changing an existing experiment" do
def same_but_different_alternative
Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange")
end
it "should reset an experiment if it is loaded with different alternatives" do
experiment.save
blue.participant_count = 5
same_experiment = same_but_different_alternative
expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"])
expect(blue.participant_count).to eq(0)
end
it "should only reset once" do
experiment.save
expect(experiment.version).to eq(0)
same_experiment = same_but_different_alternative
expect(same_experiment.version).to eq(1)
same_experiment_again = same_but_different_alternative
expect(same_experiment_again.version).to eq(1)
end
context "when metadata is changed" do
it "should increase version" do
experiment.save
experiment.metadata = { "foo" => "bar" }
expect { experiment.save }.to change { experiment.version }.by(1)
end
it "does not increase version" do
experiment.metadata = nil
experiment.save
expect { experiment.save }.to change { experiment.version }.by(0)
end
end
context "when experiment configuration is changed" do
let(:reset_manually) { false }
before do
experiment.save
allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)
green.increment_participation
green.increment_participation
experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),
goals: %w(purchase))
experiment.save
end
it "resets all alternatives" do
expect(green.participant_count).to eq(0)
expect(green.completed_count).to eq(0)
end
context "when reset_manually is set" do
let(:reset_manually) { true }
it "does not reset alternatives" do
expect(green.participant_count).to eq(2)
expect(green.completed_count).to eq(0)
end
end
end
end
describe "alternatives passed as non-strings" do
it "should throw an exception if an alternative is passed that is not a string" do
expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError)
expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError)
end
end
describe "specifying weights" do
let(:experiment_with_weight) {
Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 })
}
it "should work for a new experiment" do
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
it "should work for an existing experiment" do
experiment.save
expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])
end
end
describe "specifying goals" do
let(:experiment) {
new_experiment(["purchase"])
}
context "saving experiment" do
let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") }
before { experiment.save }
it "can find existing experiment" do
expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color")
end
it "should reset an experiment if it is loaded with different goals" do
same_but_different_goals
expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"])
end
end
it "should have goals" do
expect(experiment.goals).to eq(["purchase"])
end
context "find or create experiment" do
it "should have correct goals" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.goals).to eq(["purchase", "refund"])
experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green")
expect(experiment.goals).to eq([])
end
end
end
describe "beta probability calculation" do
it "should return a hash with the probability of each alternative being the best" do
experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange")
experiment.calc_winning_alternatives
expect(experiment.alternative_probabilities).not_to be_nil
end
it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do
experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr")
experiment.calc_winning_alternatives
expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)
end
it "should calculate the probability of being the winning alternative separately for each goal", skip: true do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
goal1 = experiment.goals[0]
goal2 = experiment.goals[1]
experiment.alternatives.each do |alternative|
alternative.participant_count = 50
alternative.set_completed_count(10, goal1)
alternative.set_completed_count(15+rand(30), goal2)
end
experiment.calc_winning_alternatives
alt = experiment.alternatives[0]
p_goal1 = alt.p_winner(goal1)
p_goal2 = alt.p_winner(goal2)
expect(p_goal1).not_to be_within(0.04).of(p_goal2)
end
it "should return nil and not re-calculate probabilities if they have already been calculated today" do
experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green")
expect(experiment.calc_winning_alternatives).not_to be nil
expect(experiment.calc_winning_alternatives).to be nil
end
end
end
<MSG> Merge pull request #40 from andreas/master
Fix specifying weights for existing experiments
<DFF> @@ -184,4 +184,20 @@ describe Split::Experiment do
lambda { Split::Experiment.find_or_create('link_enabled', true, false) }.should raise_error
end
end
-end
\ No newline at end of file
+
+ describe 'specifying weights' do
+ it "should work for a new experiment" do
+ experiment = Split::Experiment.find_or_create('link_color', { 'blue' => 1, 'red' => 2 })
+
+ experiment.alternatives.map(&:weight).should == [1, 2]
+ end
+
+ it "should work for an existing experiment" do
+ experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red')
+ experiment.save
+
+ same_experiment = Split::Experiment.find_or_create('link_color', { 'blue' => 1, 'red' => 2 })
+ same_experiment.alternatives.map(&:weight).should == [1, 2]
+ end
+ end
+end
| 17 | Merge pull request #40 from andreas/master | 1 | .rb | rb | mit | splitrb/split |
10071407 | <NME> settings.py
<BEF> from conf.default import *
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
LOCAL_DEVELOPMENT = True
if LOCAL_DEVELOPMENT:
import sys
sys.path.append(os.path.dirname(__file__))
ADMINS = (
('chishop', '[email protected]'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = os.path.join(here, 'devdatabase.db')
ACCOUNT_ACTIVATION_DAYS = 7
LOGIN_REDIRECT_URL = "/"
MANAGERS = ADMINS
DATABASE_ENGINE = ''
<MSG> Added email config to settings.py
<DFF> @@ -20,6 +20,10 @@ REGISTRATION_OPEN = True
ACCOUNT_ACTIVATION_DAYS = 7
LOGIN_REDIRECT_URL = "/"
+EMAIL_HOST = ''
+DEFAULT_FROM_EMAIL = ''
+SERVER_EMAIL = DEFAULT_FROM_EMAIL
+
MANAGERS = ADMINS
DATABASE_ENGINE = ''
| 4 | Added email config to settings.py | 0 | .py | py | bsd-3-clause | ask/chishop |
10071408 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
module Split
class Experiment
attr_accessor :name
attr_accessor :goals
attr_accessor :alternatives
def initialize(name, options = {})
options = {
:resettable => true,
}.merge(options)
@name = name.to_s
alts = options[:alternatives] || []
if alts.length == 1
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
end
end
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = load_goals_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
self.alternatives = alts
self.goals = options[:goals]
self.algorithm = options[:algorithm]
self.resettable = options[:resettable]
end
def self.all
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration
options[:metadata] = load_metadata_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
end
redis.hmset(experiment_config_key, :resettable, resettable.to_s,
:algorithm, algorithm.to_s)
self
end
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub("/", "--")
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Merge pull request #224 from nberger/refactor-experiment-initialize
Refactor Experiment#initialize
<DFF> @@ -6,13 +6,42 @@ module Split
attr_accessor :goals
attr_accessor :alternatives
+ DEFAULT_OPTIONS = {
+ :resettable => true,
+ }
+
def initialize(name, options = {})
- options = {
- :resettable => true,
- }.merge(options)
+ options = DEFAULT_OPTIONS.merge(options)
@name = name.to_s
+ alternatives = extract_alternatives_from_options(options)
+
+ if alternatives.empty? && (exp_config = Split.configuration.experiment_for(name))
+ set_alternatives_and_options(
+ alternatives: load_alternatives_from_configuration,
+ goals: load_goals_from_configuration,
+ resettable: exp_config[:resettable],
+ algorithm: exp_config[:algorithm]
+ )
+ else
+ set_alternatives_and_options(
+ alternatives: alternatives,
+ goals: options[:goals],
+ resettable: options[:resettable],
+ algorithm: options[:algorithm]
+ )
+ end
+ end
+
+ def set_alternatives_and_options(options)
+ self.alternatives = options[:alternatives]
+ self.goals = options[:goals]
+ self.resettable = options[:resettable]
+ self.algorithm = options[:algorithm]
+ end
+
+ def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
@@ -21,20 +50,7 @@ module Split
end
end
- if alts.empty?
- exp_config = Split.configuration.experiment_for(name)
- if exp_config
- alts = load_alternatives_from_configuration
- options[:goals] = load_goals_from_configuration
- options[:resettable] = exp_config[:resettable]
- options[:algorithm] = exp_config[:algorithm]
- end
- end
-
- self.alternatives = alts
- self.goals = options[:goals]
- self.algorithm = options[:algorithm]
- self.resettable = options[:resettable]
+ alts
end
def self.all
| 33 | Merge pull request #224 from nberger/refactor-experiment-initialize | 17 | .rb | rb | mit | splitrb/split |
10071409 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
module Split
class Experiment
attr_accessor :name
attr_accessor :goals
attr_accessor :alternatives
def initialize(name, options = {})
options = {
:resettable => true,
}.merge(options)
@name = name.to_s
alts = options[:alternatives] || []
if alts.length == 1
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
end
end
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = load_goals_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
self.alternatives = alts
self.goals = options[:goals]
self.algorithm = options[:algorithm]
self.resettable = options[:resettable]
end
def self.all
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration
options[:metadata] = load_metadata_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
end
redis.hmset(experiment_config_key, :resettable, resettable.to_s,
:algorithm, algorithm.to_s)
self
end
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub("/", "--")
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Merge pull request #224 from nberger/refactor-experiment-initialize
Refactor Experiment#initialize
<DFF> @@ -6,13 +6,42 @@ module Split
attr_accessor :goals
attr_accessor :alternatives
+ DEFAULT_OPTIONS = {
+ :resettable => true,
+ }
+
def initialize(name, options = {})
- options = {
- :resettable => true,
- }.merge(options)
+ options = DEFAULT_OPTIONS.merge(options)
@name = name.to_s
+ alternatives = extract_alternatives_from_options(options)
+
+ if alternatives.empty? && (exp_config = Split.configuration.experiment_for(name))
+ set_alternatives_and_options(
+ alternatives: load_alternatives_from_configuration,
+ goals: load_goals_from_configuration,
+ resettable: exp_config[:resettable],
+ algorithm: exp_config[:algorithm]
+ )
+ else
+ set_alternatives_and_options(
+ alternatives: alternatives,
+ goals: options[:goals],
+ resettable: options[:resettable],
+ algorithm: options[:algorithm]
+ )
+ end
+ end
+
+ def set_alternatives_and_options(options)
+ self.alternatives = options[:alternatives]
+ self.goals = options[:goals]
+ self.resettable = options[:resettable]
+ self.algorithm = options[:algorithm]
+ end
+
+ def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
@@ -21,20 +50,7 @@ module Split
end
end
- if alts.empty?
- exp_config = Split.configuration.experiment_for(name)
- if exp_config
- alts = load_alternatives_from_configuration
- options[:goals] = load_goals_from_configuration
- options[:resettable] = exp_config[:resettable]
- options[:algorithm] = exp_config[:algorithm]
- end
- end
-
- self.alternatives = alts
- self.goals = options[:goals]
- self.algorithm = options[:algorithm]
- self.resettable = options[:resettable]
+ alts
end
def self.all
| 33 | Merge pull request #224 from nberger/refactor-experiment-initialize | 17 | .rb | rb | mit | splitrb/split |
10071410 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
module Split
class Experiment
attr_accessor :name
attr_accessor :goals
attr_accessor :alternatives
def initialize(name, options = {})
options = {
:resettable => true,
}.merge(options)
@name = name.to_s
alts = options[:alternatives] || []
if alts.length == 1
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
end
end
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = load_goals_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
self.alternatives = alts
self.goals = options[:goals]
self.algorithm = options[:algorithm]
self.resettable = options[:resettable]
end
def self.all
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration
options[:metadata] = load_metadata_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
end
redis.hmset(experiment_config_key, :resettable, resettable.to_s,
:algorithm, algorithm.to_s)
self
end
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub("/", "--")
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Merge pull request #224 from nberger/refactor-experiment-initialize
Refactor Experiment#initialize
<DFF> @@ -6,13 +6,42 @@ module Split
attr_accessor :goals
attr_accessor :alternatives
+ DEFAULT_OPTIONS = {
+ :resettable => true,
+ }
+
def initialize(name, options = {})
- options = {
- :resettable => true,
- }.merge(options)
+ options = DEFAULT_OPTIONS.merge(options)
@name = name.to_s
+ alternatives = extract_alternatives_from_options(options)
+
+ if alternatives.empty? && (exp_config = Split.configuration.experiment_for(name))
+ set_alternatives_and_options(
+ alternatives: load_alternatives_from_configuration,
+ goals: load_goals_from_configuration,
+ resettable: exp_config[:resettable],
+ algorithm: exp_config[:algorithm]
+ )
+ else
+ set_alternatives_and_options(
+ alternatives: alternatives,
+ goals: options[:goals],
+ resettable: options[:resettable],
+ algorithm: options[:algorithm]
+ )
+ end
+ end
+
+ def set_alternatives_and_options(options)
+ self.alternatives = options[:alternatives]
+ self.goals = options[:goals]
+ self.resettable = options[:resettable]
+ self.algorithm = options[:algorithm]
+ end
+
+ def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
@@ -21,20 +50,7 @@ module Split
end
end
- if alts.empty?
- exp_config = Split.configuration.experiment_for(name)
- if exp_config
- alts = load_alternatives_from_configuration
- options[:goals] = load_goals_from_configuration
- options[:resettable] = exp_config[:resettable]
- options[:algorithm] = exp_config[:algorithm]
- end
- end
-
- self.alternatives = alts
- self.goals = options[:goals]
- self.algorithm = options[:algorithm]
- self.resettable = options[:resettable]
+ alts
end
def self.all
| 33 | Merge pull request #224 from nberger/refactor-experiment-initialize | 17 | .rb | rb | mit | splitrb/split |
10071411 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
end
end
shared_examples_for "a disabled test" do
describe 'ab_test' do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> allow for a custom exclude logic
this is just an example implementation for discussion, readme and docs are still missing.
<DFF> @@ -380,6 +380,26 @@ describe Split::Helper do
end
end
+
+ describe 'when providing custom ignore logic' do
+ context "using a proc to configure custom logic" do
+
+ before(:each) do
+ Split.configure do |c|
+ c.ignore_filter = proc{|request| !!"i_am_going_to_be_disabled" }
+ end
+ end
+
+ it "ignores the ab_test" do
+ ab_test('link_color', 'blue', 'red')
+
+ red_count = Split::Alternative.new('red', 'link_color').participant_count
+ blue_count = Split::Alternative.new('blue', 'link_color').participant_count
+ (red_count + blue_count).should be(0)
+ end
+ end
+ end
+
shared_examples_for "a disabled test" do
describe 'ab_test' do
| 20 | allow for a custom exclude logic | 0 | .rb | rb | mit | splitrb/split |
10071412 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
end
end
shared_examples_for "a disabled test" do
describe 'ab_test' do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> allow for a custom exclude logic
this is just an example implementation for discussion, readme and docs are still missing.
<DFF> @@ -380,6 +380,26 @@ describe Split::Helper do
end
end
+
+ describe 'when providing custom ignore logic' do
+ context "using a proc to configure custom logic" do
+
+ before(:each) do
+ Split.configure do |c|
+ c.ignore_filter = proc{|request| !!"i_am_going_to_be_disabled" }
+ end
+ end
+
+ it "ignores the ab_test" do
+ ab_test('link_color', 'blue', 'red')
+
+ red_count = Split::Alternative.new('red', 'link_color').participant_count
+ blue_count = Split::Alternative.new('blue', 'link_color').participant_count
+ (red_count + blue_count).should be(0)
+ end
+ end
+ end
+
shared_examples_for "a disabled test" do
describe 'ab_test' do
| 20 | allow for a custom exclude logic | 0 | .rb | rb | mit | splitrb/split |
10071413 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
end
end
shared_examples_for "a disabled test" do
describe 'ab_test' do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> allow for a custom exclude logic
this is just an example implementation for discussion, readme and docs are still missing.
<DFF> @@ -380,6 +380,26 @@ describe Split::Helper do
end
end
+
+ describe 'when providing custom ignore logic' do
+ context "using a proc to configure custom logic" do
+
+ before(:each) do
+ Split.configure do |c|
+ c.ignore_filter = proc{|request| !!"i_am_going_to_be_disabled" }
+ end
+ end
+
+ it "ignores the ab_test" do
+ ab_test('link_color', 'blue', 'red')
+
+ red_count = Split::Alternative.new('red', 'link_color').participant_count
+ blue_count = Split::Alternative.new('blue', 'link_color').participant_count
+ (red_count + blue_count).should be(0)
+ end
+ end
+ end
+
shared_examples_for "a disabled test" do
describe 'ab_test' do
| 20 | allow for a custom exclude logic | 0 | .rb | rb | mit | splitrb/split |
10071414 | <NME> AUTHORS
<BEF> Ask Solem <[email protected]>
Rune Halvorsen <[email protected]>
Russell Sim <[email protected]>
Brian Rosner <[email protected]>
Hugo Lopes Tavares <[email protected]>
Sverre Johansen <[email protected]>
Bo Shi <[email protected]>
Carl Meyer <[email protected]>
Vinícius das Chagas Silva <[email protected]>
Vanderson Mota dos Santos <[email protected]>
Stefan Foulis <[email protected]>
Michael Richardson <[email protected]>
Halldór Rúnarsson <[email protected]>
David Cramer <[email protected]>
<MSG> Adds David Cramer to AUTHORS
<DFF> @@ -11,3 +11,4 @@ Vanderson Mota dos Santos <[email protected]>
Stefan Foulis <[email protected]>
Michael Richardson <[email protected]>
Halldór Rúnarsson <[email protected]>
+David Cramer <[email protected]>
| 1 | Adds David Cramer to AUTHORS | 0 | AUTHORS | bsd-3-clause | ask/chishop |
|
10071415 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
end
s.add_development_dependency 'rake'
s.add_development_dependency 'bundler', '~> 1.6.5'
s.add_development_dependency 'rspec', '~> 3.0'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'coveralls'
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Looser bundler dependency
<DFF> @@ -29,7 +29,7 @@ Gem::Specification.new do |s|
end
s.add_development_dependency 'rake'
- s.add_development_dependency 'bundler', '~> 1.6.5'
+ s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'rspec', '~> 3.0'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'coveralls'
| 1 | Looser bundler dependency | 1 | .gemspec | gemspec | mit | splitrb/split |
10071416 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
end
s.add_development_dependency 'rake'
s.add_development_dependency 'bundler', '~> 1.6.5'
s.add_development_dependency 'rspec', '~> 3.0'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'coveralls'
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Looser bundler dependency
<DFF> @@ -29,7 +29,7 @@ Gem::Specification.new do |s|
end
s.add_development_dependency 'rake'
- s.add_development_dependency 'bundler', '~> 1.6.5'
+ s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'rspec', '~> 3.0'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'coveralls'
| 1 | Looser bundler dependency | 1 | .gemspec | gemspec | mit | splitrb/split |
10071417 | <NME> split.gemspec
<BEF> # -*- encoding: utf-8 -*-
# frozen_string_literal: true
$:.push File.expand_path("../lib", __FILE__)
require "split/version"
Gem::Specification.new do |s|
s.name = "split"
s.version = Split::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Andrew Nesbitt"]
s.licenses = ["MIT"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/splitrb/split"
s.summary = "Rack based split testing framework"
s.metadata = {
"homepage_uri" => "https://github.com/splitrb/split",
"changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md",
"source_code_uri" => "https://github.com/splitrb/split",
"bug_tracker_uri" => "https://github.com/splitrb/split/issues",
"wiki_uri" => "https://github.com/splitrb/split/wiki",
"mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby"
}
s.required_ruby_version = ">= 2.5.0"
s.required_rubygems_version = ">= 2.0.0"
end
s.add_development_dependency 'rake'
s.add_development_dependency 'bundler', '~> 1.6.5'
s.add_development_dependency 'rspec', '~> 3.0'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'coveralls'
s.add_development_dependency "bundler", ">= 1.17"
s.add_development_dependency "simplecov", "~> 0.15"
s.add_development_dependency "rack-test", "~> 2.0"
s.add_development_dependency "rake", "~> 13"
s.add_development_dependency "rspec", "~> 3.7"
s.add_development_dependency "pry", "~> 0.10"
s.add_development_dependency "rails", ">= 5.0"
end
<MSG> Looser bundler dependency
<DFF> @@ -29,7 +29,7 @@ Gem::Specification.new do |s|
end
s.add_development_dependency 'rake'
- s.add_development_dependency 'bundler', '~> 1.6.5'
+ s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'rspec', '~> 3.0'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'coveralls'
| 1 | Looser bundler dependency | 1 | .gemspec | gemspec | mit | splitrb/split |
10071418 | <NME> settings.py
<BEF> from conf.default import *
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
LOCAL_DEVELOPMENT = True
if LOCAL_DEVELOPMENT:
import sys
sys.path.append(os.path.dirname(__file__))
ADMINS = (
('chishop', '[email protected]'),
)
# change to False if you do not want Django's default server to serve static pages
LOCAL_DEVELOPMENT = True
ACCOUNT_ACTIVATION_DAYS = 7
LOGIN_REDIRECT_URL = "/"
DATABASE_PORT = ''
<MSG> Set REGISTRATION_OPEN in settings
<DFF> @@ -16,6 +16,7 @@ DJANGOPYPI_RELEASE_UPLOAD_TO = 'dists'
# change to False if you do not want Django's default server to serve static pages
LOCAL_DEVELOPMENT = True
+REGISTRATION_OPEN = True
ACCOUNT_ACTIVATION_DAYS = 7
LOGIN_REDIRECT_URL = "/"
| 1 | Set REGISTRATION_OPEN in settings | 0 | .py | py | bsd-3-clause | ask/chishop |
10071419 | <NME> CHANGELOG.md
<BEF> ## 4.0.1 (December 30th, 2021)
Bugfixes:
- ab_test must return metadata on error or if split is disabled/excluded user (@andrehjr, #622)
- Fix versioned experiments when used with allow_multiple_experiments=control (@andrehjr, #613)
- Only block Pinterest bot (@huoxito, #606)
- Respect experiment defaults when loading experiments in initializer. (@mattwd7, #599)
- Removes metadata key when it updated to nil (@andrehjr, #633)
- Force experiment does not count for metrics (@andrehjr, #637)
- Fix cleanup_old_versions! misbehaviour (@serggl, #661)
Features:
- Make goals accessible via on_trial_complete callbacks (@robin-phung, #625)
- Replace usage of SimpleRandom with RubyStats(Used for Beta Distribution RNG) (@andrehjr, #616)
- Introduce enable/disable experiment cohorting (@robin-phung, #615)
- Add on_experiment_winner_choose callback (@GenaMinenkov, #574)
- Drop support for Rails < 5 (@andrehkr, #607)
- Bump minimum required redis to 4.2 (@andrehjr, #628)
- Removed repeated loading from config (@robin-phung, #619)
## 3.4.1 (November 12th, 2019)
- Simplify RedisInterface usage when persisting Experiment alternatives (@andrehjr, #632)
- Remove redis_url impl. Deprecated on version 2.2 (@andrehjr, #631)
- Remove thread_safe config as redis-rb is thread_safe by default (@andrehjr, #630)
- Fix typo of in `Split::Trial` class variable (TomasBarry, #644)
- Single HSET to update values, instead of multiple ones (@andrehjr, #640)
- Use Redis#hmset to keep compatibility with Redis < 4.0 (@andrehjr, #659)
- Remove 'set' parsing for alternatives. Sets were used as storage and deprecated on 0.x (@andrehjr, #639)
- Adding documentation related to what is stored on cookies. (@andrehjr, #634)
- Keep railtie defined under the Split gem namespace (@avit, #666)
- Update RSpec helper to support block syntax (@clowder, #665)
## 3.4.1 (November 12th, 2019)
Bugfixes:
- Reference ActionController directly when including split helpers, to avoid breaking Rails API Controllers (@andrehjr, #602)
## 3.4.0 (November 9th, 2019)
Features:
- Improve DualAdapter (@santib, #588), adds a new configuration for the DualAdapter, making it possible to keep consistency for logged_out/logged_in users. It's a opt-in flag. No Behavior was changed on this release.
- Make dashboard pagination default "per" param configurable (@alopatin, #597)
Bugfixes:
- Fix `force_alternative` for experiments with incremented version (@giraffate, #568)
- Persist alternative weights (@giraffate, #570)
- Combined experiment performance improvements (@gnanou, #575)
- Handle correctly case when ab_finished is called before ab_test for a user (@gnanou, #577)
- When loading active_experiments, it should not look into user's 'finished' keys (@andrehjr, #582)
Misc:
- Remove `rubyforge_project` from gemspec (@giraffate, #583)
- Fix URLs to replace http with https (@giraffate , #584)
- Lazily include split helpers in ActionController::Base (@hasghari, #586)
- Fix unused variable warnings (@andrehjr, #592)
- Fix ruby warnings (@andrehjr, #593)
- Update rubocop.yml config (@andrehjr, #594)
- Add frozen_string_literal to all files that were missing it (@andrehjr, #595)
## 3.3.2 (April 12th, 2019)
Features:
- Added uptime robot to configuration.rb (@razel1982, #556)
- Check to see if being run in Rails application and run in before_initialize (@husteadrobert, #555)
Bugfixes:
- Fix error message interpolation (@hanibash, #553)
- Fix Bigdecimal warnings (@agraves, #551)
- Avoid hitting up on redis for robots/excluded users. (@andrehjr, #544)
- Checks for defined?(request) on Helper#exclude_visitor?. (@andrehjr)
Misc:
- Update travis to add Rails 6 (@edmilton, #559)
- Fix broken specs in developement environment (@dougpetronilio, #557)
## 3.3.1 (January 11th, 2019)
Features:
- Filter some more bots (@janosch-x, #542)
Bugfixes:
- Fix Dashboard Pagination Helper typo (@cattekin, #541)
- Do not storage alternative in cookie if experiment has a winner (@sadhu89, #539)
- fix user participating alternative not found (@NaturalHokke, #536)
Misc:
- Tweak RSpec instructions (@eliotsykes, #540)
- Improve README regarding rspec usage (@vermaxik, #538)
## 3.3.0 (August 13th, 2018)
Features:
- Added pagination for dashboard (@GeorgeGorbanev, #518)
- Add Facebot crawler to list of bots (@pfeiffer, #530)
- Ignore previewing requests (@pfeiffer, #531)
- Fix binding of ignore_filter (@pfeiffer, #533)
Bugfixes:
- Fix cookie header duplication (@andrehjr, #522)
Performance:
- Improve performance of RedisInterface#make_list_length by using LTRIM command (@mlovic, #509)
Misc:
- Update development dependencies
- test rails 5.2 on travis (@lostapathy, #524)
- update ruby versions for travis (@lostapathy, #525)
## 3.2.0 (September 21st, 2017)
Features:
- Allow configuration of how often winning alternatives are recalculated (@patbl, #501)
Bugfixes:
- Avoid z_score numeric exception for conversion rates >1 (@cmantas, #503)
- Fix combined experiments (@semanticart, #502)
## 3.1.1 (August 30th, 2017)
Bugfixes:
- Bring back support for ruby 1.9.3 and greater (rubygems 2.0.0 or greater now required) (@patbl, #498)
Misc:
- Document testing with RSpec (@eliotsykes, #495)
## 3.1.0 (August 14th, 2017)
Features:
- Support for combined experiments (@daviddening, #493)
- Rewrite CookieAdapter to work with Rack::Request and Rack::Response directly (@andrehjr, #490)
- Enumeration of a User's Experiments that Respects the db_failover Option(@MarkRoddy, #487)
Bugfixes:
- Blocked a few more common bot user agents (@kylerippey, #485)
Misc:
- Repository Audit by Maintainer.io (@RichardLitt, #484)
- Update development dependencies
- Test on ruby 2.4.1
- Test compatibility with rails 5.1
- Add uris to metadata section in gemspec
## 3.0.0 (March 30th, 2017)
Features:
- added block randomization algorithm and specs (@hulleywood, #475)
- Add ab_record_extra_info to allow record extra info to alternative and display on dashboard. (@tranngocsam, #460)
Bugfixes:
- Avoid crashing on Ruby 2.4 for numeric strings (@flori, #470)
- Fix issue where redis isn't required (@tomciopp , #466)
Misc:
- Avoid variable_size_secure_compare private method (@eliotsykes, #465)
## 2.2.0 (November 11th, 2016)
**Backwards incompatible!** Redis keys are renamed. Please make sure all running tests are completed before you upgrade, as they will reset.
Features:
- Remove dependency on Redis::Namespace (@bschaeffer, #425)
- Make resetting on experiment change optional (@moggyboy, #430)
- Add ability to force alternative on dashboard (@ccallebs, #437)
Bugfixes:
- Fix variations reset across page loads for multiple=control and improve coverage (@Vasfed, #432)
Misc:
- Remove Explicit Return (@BradHudson, #441)
- Update Redis config docs (@bschaeffer, #422)
- Harden HTTP Basic snippet against timing attacks (@eliotsykes, #443)
- Removed a couple old ruby 1.8 hacks (@andrew, #456)
- Run tests on rails 5 (@andrew, #457)
- Fixed a few codeclimate warnings (@andrew, #458)
- Use codeclimate for test coverage (@andrew #455)
## 2.1.0 (August 8th, 2016)
Features:
- Support REDIS_PROVIDER variable used in Heroku (@kartikluke, #426)
## 2.0.0 (July 17th, 2016)
Breaking changes:
- Removed deprecated `finished` and `begin_experiment` methods
- Namespaced override param to avoid potential clashes (@henrik, #398)
## 1.7.0 (June 28th, 2016)
Features:
- Running concurrent experiments on same endpoint/view (@karmakaze, #421)
## 1.6.0 (June 16th, 2016)
Features:
- Add Dual Redis(logged-in)/cookie(logged-out) persistence adapter (@karmakaze, #420)
## 1.5.0 (June 8th, 2016)
Features:
- Add `expire_seconds:` TTL option to RedisAdapter (@karmakaze, #409)
- Optional custom persistence adapter (@ndelage, #411)
Misc:
- Use fakeredis for testing (@andrew, #412)
## 1.4.5 (June 7th, 2016)
Bugfixes:
- FIX Negative numbers on non-finished (@divineforest, #408)
- Eliminate extra RedisAdapter hget (@karmakaze, #407)
- Remove unecessary code from Experiment class (@pakallis, #391, #392, #393)
Misc:
- Simplify Configuration#normalized_experiments (@pakallis, #395)
- Clarify test running instructions (@henrik, #397)
## 1.4.4 (May 9th, 2016)
Bugfixes:
- Increment participation if store override is true and no experiment key exists (@spheric, #380)
Misc:
- Deprecated `finished` method in favour of `ab_finished` (@andreibondarev, #389)
- Added minimum version requirement to simple-random
- Clarify finished with first option being a hash in Readme (@henrik, #382)
- Refactoring the User abstraction (@andreibondarev, #384)
## 1.4.3 (April 28th, 2016)
Features:
- add on_trial callback whenever a trial is started (@mtyeh411, #375)
Bugfixes:
- Allow algorithm configuration at experiment level (@007sumit, #376)
Misc:
- only choose override if it exists as valid alternative (@spheric, #377)
## 1.4.2 (April 25th, 2016)
Misc:
- Deprecated some legacy methods (@andreibondarev, #374)
## 1.4.1 (April 21st, 2016)
Bugfixes:
- respect manual start configuration after an experiment has been deleted (@mtyeh411, #372)
Misc:
- Introduce goals collection to reduce complexity of Experiment#save (@pakallis, #365)
- Revise specs according to http://betterspecs.org/ (@hkliya, #369)
## 1.4.0 (April 2nd, 2016)
Features:
- Added experiment filters to dashboard (@ccallebs, #363, #364)
- Added Contributor Covenant Code of Conduct
## 1.3.2 (January 2nd, 2016)
Bugfixes:
- Fix deleting experiments in from the updated dashboard (@craigmcnamara, #352)
## 1.3.1 (January 1st, 2016)
Bugfixes:
- Fix the dashboard for experiments with ‘/‘ in the name. (@craigmcnamara, #349)
## 1.3.0 (October 20th, 2015)
Features:
- allow for custom redis_url different from ENV variable (@davidgrieser, #323)
- add ability to change the length of the persistence cookie (@peterylai, #335)
Bugfixes:
- Rescue from Redis::BaseError instead of Redis::CannotConnectError (@nfm, #342)
- Fix active experiments when experiment is on a later version (@ndrisso, #331)
- Fix caching of winning alternative (@nfm, #329)
Misc:
- Remove duplication from Experiment#save (@pakallis, #333)
- Remove unnecessary argument from Experiment#write_to_alternative (@t4deu, #332)
## 1.2.1 (May 17th, 2015)
Features:
- Handle redis DNS resolution failures gracefully (@fusion2004, #310)
- Push metadata to ab_test block (@ekorneeff, #296)
- Helper methods are now private when included in controllers (@ipoval, #303)
Bugfixes:
- Return an empty hash as metadata when Split is disabled (@tomasdundacek, #313)
- Don't use capture helper from ActionView (@tomasdundacek, #312)
Misc:
- Remove body "max-width" from dashboard (@xicreative, #299)
- fix private for class methods (@ipoval, #301)
- minor memoization fix in spec (@ipoval, #304)
- Minor documentation fixes (#295, #297, #305, #308)
## 1.2.0 (January 24th, 2015)
Features:
- Configure redis using environment variables if available (@saratovsource , #293)
- Store metadata on experiment configuration (@dekz, #291)
Bugfixes:
- Revert the Trial#complete! public API to support noargs (@dekz, #292)
## 1.1.0 (January 9th, 2015)
Changes:
- Public class methods on `Split::Experiment` (e.g., `find_or_create`)
have been moved to `Split::ExperimentCatalog`.
Features:
- Decouple trial from Split::Helper (@joshdover, #286)
- Helper method for Active Experiments (@blahblahblah-, #273)
Misc:
- Use the new travis container based infrastructure for tests (@andrew, #280)
## 1.0.0 (October 12th, 2014)
Changes:
- Remove support for Ruby 1.8.7 and Rails 2.3 (@qpowell, #271)
## 0.8.0 (September 25th, 2014)
Features:
- Added new way to calculate the probability an alternative is the winner (@caser, #266, #251)
- support multiple metrics per experiment (@stevenou, #260)
Bugfixes:
- Avoiding call to params in EncapsulatedHelper (@afn, #257)
## 0.7.3 (September 16th, 2014)
Features:
- Disable all split tests via a URL parameter (@hwartig, #263)
Bugfixes:
- Correctly escape experiment names on dashboard (@ecaron, #265)
- Handle redis connection exception error properly (@andrew, #245)
## 0.7.2 (June 12th, 2014)
Features:
- Show metrics on the dashboard (@swrobel, #241)
Bugfixes:
- Avoid nil error with ExperimentCatalog when upgrading (@danielschwartz, #253)
- [SECURITY ISSUE] Only allow known alternatives as query param overrides (@ankane, #255)
## 0.7.1 (March 20th, 2014)
Features:
- You can now reopen experiment from the dashboard (@mikezaby, #235)
Misc:
- Internal code tidy up (@IanVaughan, #238)
## 0.7.0 (December 26th, 2013)
Features:
- Significantly improved z-score algorithm (@caser ,#221)
- Better sorting of Experiments on dashboard (@wadako111, #218)
Bugfixes:
- Fixed start button not being displayed in some cases (@vigosan, #219)
Misc:
- Experiment#initialize refactoring (@nberger, #224)
- Extract ExperimentStore into a seperate class (@nberger, #225)
## 0.6.6 (October 15th, 2013)
Features:
- Sort experiments on Dashboard so "active" ones without a winner appear first (@swrobel, #204)
- Starting tests manually (@duksis, #209)
Bugfixes:
- Only trigger completion callback with valid Trial (@segfaultAX, #208)
- Fixed bug with `resettable` when using `normalize_experiments` (@jonashuckestein, #213)
Misc:
- Added more bots to filter list (@lbeder, #214, #215, #216)
## 0.6.5 (August 23, 2013)
Features:
- Added Redis adapter for persisting experiments across sessions (@fengb, #203)
Misc:
- Expand upon algorithms section in README (@swrobel, #200)
## 0.6.4 (August 8, 2013)
Features:
- Add hooks for experiment deletion and resetting (@craigmcnamara, #198)
- Allow Split::Helper to be used outside of a controller (@nfm, #190)
- Show current Rails/Rack Env in dashboard (@rceee, #187)
Bugfixes:
- Fix whiplash algorithm when using goals (@swrobel, #193)
Misc:
- Refactor dashboard js (@buddhamagnet)
## 0.6.3 (July 8, 2013)
Features:
- Add hooks for Trial#choose! and Trial#complete! (@bmarini, #176)
Bugfixes:
- Stores and parses Experiment's start_time as a UNIX integer (@joeroot, #177)
## 0.6.2 (June 6, 2013)
Features:
- Rails 2.3 compatibility (@bhcarpenter, #167)
- Adding possibility to store overridden alternative (@duksis, #173)
Misc:
- Now testing against multiple versions of rails
## 0.6.1 (May 4, 2013)
Bugfixes:
- Use the specified algorithm for the experiment instead of the default (@woodhull, #165)
Misc:
- Ensure experiements are valid when configuring (@ashmckenzie, #159)
- Allow arrays to be passed to ab_test (@fenelon, #156)
## 0.6.0 (April 4, 2013)
Features:
- Support for Ruby 2.0.0 (@phoet, #142)
- Multiple Goals (@liujin, #109)
- Ignoring IPs using Regular Expressions (@waynemoore, #119)
- Added ability to add more bots to the default list (@themgt, #140)
- Allow custom configuration of user blocking logic (@phoet , #148)
Bugfixes:
- Fixed regression in handling of config files (@iangreenleaf, #115)
- Fixed completion rate increases for experiments users aren't participating in (@philnash, #67)
- Handle exceptions from invalid JSON in cookies (@iangreenleaf, #126)
Misc:
- updated minimum json version requirement
- Refactor Yaml Configuration (@rtwomey, #124)
- Refactoring of Experiments (@iangreenleaf @tamird, #117 #118)
- Added more known Bots, including Pingdom, Bing, YandexBot (@julesie, @zinkkrysty, @dimko)
- Improved Readme (@iangreenleaf @phoet)
## 0.5.0 (January 28, 2013)
Features:
- Persistence Adapters: Cookies and Session (@patbenatar, #98)
- Configure experiments from a hash (@iangreenleaf, #97)
- Pluggable sampling algorithms (@woodhull, #105)
Bugfixes:
- Fixed negative number of non-finished rates (@philnash, #83)
- Fixed behaviour of finished(:reset => false) (@philnash, #88)
- Only take into consideration positive z-scores (@thomasmaas, #96)
- Amended ab_test method to raise ArgumentError if passed integers or symbols as
alternatives (@buddhamagnet, #81)
## 0.4.6 (October 28, 2012)
Features:
- General code quality improvements (@buddhamagnet, #79)
Bugfixes:
- Don't increment the experiment counter if user has finished (@dimko, #78)
- Fixed an incorrect test (@jaywengrow, #74)
## 0.4.5 (August 30, 2012)
Bugfixes:
- Fixed header gradient in FF/Opera (@philnash, #69)
- Fixed reseting of experiment in session (@apsoto, #43)
## 0.4.4 (August 9, 2012)
Features:
- Allow parameter overrides, even without Redis. (@bhcarpenter, #62)
Bugfixes:
- Fixes version number always increasing when alternatives are changed (@philnash, #63)
- updated guard-rspec to version 1.2
## 0.4.3 (July 8, 2012)
Features:
- redis failover now recovers from all redis-related exceptions
## 0.4.2 (June 1, 2012)
Features:
- Now works with v3.0 of redis gem
Bugfixes:
- Fixed redis failover on Rubinius
## 0.4.1 (April 6, 2012)
Features:
- Added configuration option to disable Split testing (@ilyakatz, #45)
Bugfixes:
- Fix weights for existing experiments (@andreas, #40)
- Fixed dashboard range error (@andrew, #42)
## 0.4.0 (March 7, 2012)
**IMPORTANT**
If using ruby 1.8.x and weighted alternatives you should always pass the control alternative through as the second argument with any other alternatives as a third argument because the order of the hash is not preserved in ruby 1.8, ruby 1.9 users are not affected by this bug.
Features:
- Experiments now record when they were started (@vrish88, #35)
- Old versions of experiments in sessions are now cleaned up
- Avoid users participating in multiple experiments at once (#21)
Bugfixes:
- Overriding alternatives doesn't work for weighted alternatives (@layflags, #34)
- confidence_level helper should handle tiny z-scores (#23)
## 0.3.3 (February 16, 2012)
Bugfixes:
- Fixed redis failover when a block was passed to ab_test (@layflags, #33)
## 0.3.2 (February 12, 2012)
Features:
- Handle redis errors gracefully (@layflags, #32)
## 0.3.1 (November 19, 2011)
Features:
- General code tidy up (@ryanlecompte, #22, @mocoso, #28)
- Lazy loading data from Redis (@lautis, #25)
Bugfixes:
- Handle unstarted experiments (@mocoso, #27)
- Relaxed Sinatra version requirement (@martinclu, #24)
## 0.3.0 (October 9, 2011)
Features:
- Redesigned dashboard (@mrappleton, #17)
- Use atomic increments in redis for better concurrency (@lautis, #18)
- Weighted alternatives
Bugfixes:
- Fix to allow overriding of experiments that aren't on version 1
## 0.2.4 (July 18, 2011)
Features:
- Added option to finished to not reset the users session
Bugfixes:
- Only allow strings as alternatives, fixes strange errors when passing true/false or symbols
## 0.2.3 (June 26, 2011)
Features:
- Experiments can now be deleted from the dashboard
- ab_test helper now accepts a block
- Improved dashboard
Bugfixes:
- After resetting an experiment, existing users of that experiment will also be reset
## 0.2.2 (June 11, 2011)
Features:
- Updated redis-namespace requirement to 1.0.3
- Added a configuration object for changing options
- Robot regex can now be changed via a configuration options
- Added ability to ignore visits from specified IP addresses
- Dashboard now shows percentage improvement of alternatives compared to the control
- If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives
Bugfixes:
- Saving an experiment multiple times no longer creates duplicate alternatives
## 0.2.1 (May 29, 2011)
Bugfixes:
- Convert legacy sets to lists to avoid exceptions during upgrades from 0.1.x
## 0.2.0 (May 29, 2011)
Features:
- Override an alternative via a url parameter
- Experiments can now be reset from the dashboard
- The first alternative is now considered the control
- General dashboard usability improvements
- Robots are ignored and given the control alternative
Bugfixes:
- Alternatives are now store in a list rather than a set to ensure consistent ordering
- Fixed diving by zero errors
## 0.1.1 (May 18, 2011)
Bugfixes:
- More Robust conversion rate display on dashboard
- Ensure `Split::Version` is available everywhere, fixed dashboard
## 0.1.0 (May 17, 2011)
Initial Release
<MSG> update changelog
<DFF> @@ -17,6 +17,9 @@ Misc:
- Drop support for Rails < 5 (@andrehkr, #607)
- Bump minimum required redis to 4.2 (@andrehjr, #628)
- Removed repeated loading from config (@robin-phung, #619)
+- Simplify RedisInterface usage when persisting Experiment alternatives (@andrehjr, #632)
+- Remove redis_url impl. Deprecated on version 2.2 (@andrehjr, #631)
+- Remove thread_safe config as redis-rb is thread_safe by default (@andrehjr, #630)
## 3.4.1 (November 12th, 2019)
| 3 | update changelog | 0 | .md | md | mit | splitrb/split |
10071420 | <NME> CHANGELOG.md
<BEF> ## 4.0.1 (December 30th, 2021)
Bugfixes:
- ab_test must return metadata on error or if split is disabled/excluded user (@andrehjr, #622)
- Fix versioned experiments when used with allow_multiple_experiments=control (@andrehjr, #613)
- Only block Pinterest bot (@huoxito, #606)
- Respect experiment defaults when loading experiments in initializer. (@mattwd7, #599)
- Removes metadata key when it updated to nil (@andrehjr, #633)
- Force experiment does not count for metrics (@andrehjr, #637)
- Fix cleanup_old_versions! misbehaviour (@serggl, #661)
Features:
- Make goals accessible via on_trial_complete callbacks (@robin-phung, #625)
- Replace usage of SimpleRandom with RubyStats(Used for Beta Distribution RNG) (@andrehjr, #616)
- Introduce enable/disable experiment cohorting (@robin-phung, #615)
- Add on_experiment_winner_choose callback (@GenaMinenkov, #574)
- Drop support for Rails < 5 (@andrehkr, #607)
- Bump minimum required redis to 4.2 (@andrehjr, #628)
- Removed repeated loading from config (@robin-phung, #619)
## 3.4.1 (November 12th, 2019)
- Simplify RedisInterface usage when persisting Experiment alternatives (@andrehjr, #632)
- Remove redis_url impl. Deprecated on version 2.2 (@andrehjr, #631)
- Remove thread_safe config as redis-rb is thread_safe by default (@andrehjr, #630)
- Fix typo of in `Split::Trial` class variable (TomasBarry, #644)
- Single HSET to update values, instead of multiple ones (@andrehjr, #640)
- Use Redis#hmset to keep compatibility with Redis < 4.0 (@andrehjr, #659)
- Remove 'set' parsing for alternatives. Sets were used as storage and deprecated on 0.x (@andrehjr, #639)
- Adding documentation related to what is stored on cookies. (@andrehjr, #634)
- Keep railtie defined under the Split gem namespace (@avit, #666)
- Update RSpec helper to support block syntax (@clowder, #665)
## 3.4.1 (November 12th, 2019)
Bugfixes:
- Reference ActionController directly when including split helpers, to avoid breaking Rails API Controllers (@andrehjr, #602)
## 3.4.0 (November 9th, 2019)
Features:
- Improve DualAdapter (@santib, #588), adds a new configuration for the DualAdapter, making it possible to keep consistency for logged_out/logged_in users. It's a opt-in flag. No Behavior was changed on this release.
- Make dashboard pagination default "per" param configurable (@alopatin, #597)
Bugfixes:
- Fix `force_alternative` for experiments with incremented version (@giraffate, #568)
- Persist alternative weights (@giraffate, #570)
- Combined experiment performance improvements (@gnanou, #575)
- Handle correctly case when ab_finished is called before ab_test for a user (@gnanou, #577)
- When loading active_experiments, it should not look into user's 'finished' keys (@andrehjr, #582)
Misc:
- Remove `rubyforge_project` from gemspec (@giraffate, #583)
- Fix URLs to replace http with https (@giraffate , #584)
- Lazily include split helpers in ActionController::Base (@hasghari, #586)
- Fix unused variable warnings (@andrehjr, #592)
- Fix ruby warnings (@andrehjr, #593)
- Update rubocop.yml config (@andrehjr, #594)
- Add frozen_string_literal to all files that were missing it (@andrehjr, #595)
## 3.3.2 (April 12th, 2019)
Features:
- Added uptime robot to configuration.rb (@razel1982, #556)
- Check to see if being run in Rails application and run in before_initialize (@husteadrobert, #555)
Bugfixes:
- Fix error message interpolation (@hanibash, #553)
- Fix Bigdecimal warnings (@agraves, #551)
- Avoid hitting up on redis for robots/excluded users. (@andrehjr, #544)
- Checks for defined?(request) on Helper#exclude_visitor?. (@andrehjr)
Misc:
- Update travis to add Rails 6 (@edmilton, #559)
- Fix broken specs in developement environment (@dougpetronilio, #557)
## 3.3.1 (January 11th, 2019)
Features:
- Filter some more bots (@janosch-x, #542)
Bugfixes:
- Fix Dashboard Pagination Helper typo (@cattekin, #541)
- Do not storage alternative in cookie if experiment has a winner (@sadhu89, #539)
- fix user participating alternative not found (@NaturalHokke, #536)
Misc:
- Tweak RSpec instructions (@eliotsykes, #540)
- Improve README regarding rspec usage (@vermaxik, #538)
## 3.3.0 (August 13th, 2018)
Features:
- Added pagination for dashboard (@GeorgeGorbanev, #518)
- Add Facebot crawler to list of bots (@pfeiffer, #530)
- Ignore previewing requests (@pfeiffer, #531)
- Fix binding of ignore_filter (@pfeiffer, #533)
Bugfixes:
- Fix cookie header duplication (@andrehjr, #522)
Performance:
- Improve performance of RedisInterface#make_list_length by using LTRIM command (@mlovic, #509)
Misc:
- Update development dependencies
- test rails 5.2 on travis (@lostapathy, #524)
- update ruby versions for travis (@lostapathy, #525)
## 3.2.0 (September 21st, 2017)
Features:
- Allow configuration of how often winning alternatives are recalculated (@patbl, #501)
Bugfixes:
- Avoid z_score numeric exception for conversion rates >1 (@cmantas, #503)
- Fix combined experiments (@semanticart, #502)
## 3.1.1 (August 30th, 2017)
Bugfixes:
- Bring back support for ruby 1.9.3 and greater (rubygems 2.0.0 or greater now required) (@patbl, #498)
Misc:
- Document testing with RSpec (@eliotsykes, #495)
## 3.1.0 (August 14th, 2017)
Features:
- Support for combined experiments (@daviddening, #493)
- Rewrite CookieAdapter to work with Rack::Request and Rack::Response directly (@andrehjr, #490)
- Enumeration of a User's Experiments that Respects the db_failover Option(@MarkRoddy, #487)
Bugfixes:
- Blocked a few more common bot user agents (@kylerippey, #485)
Misc:
- Repository Audit by Maintainer.io (@RichardLitt, #484)
- Update development dependencies
- Test on ruby 2.4.1
- Test compatibility with rails 5.1
- Add uris to metadata section in gemspec
## 3.0.0 (March 30th, 2017)
Features:
- added block randomization algorithm and specs (@hulleywood, #475)
- Add ab_record_extra_info to allow record extra info to alternative and display on dashboard. (@tranngocsam, #460)
Bugfixes:
- Avoid crashing on Ruby 2.4 for numeric strings (@flori, #470)
- Fix issue where redis isn't required (@tomciopp , #466)
Misc:
- Avoid variable_size_secure_compare private method (@eliotsykes, #465)
## 2.2.0 (November 11th, 2016)
**Backwards incompatible!** Redis keys are renamed. Please make sure all running tests are completed before you upgrade, as they will reset.
Features:
- Remove dependency on Redis::Namespace (@bschaeffer, #425)
- Make resetting on experiment change optional (@moggyboy, #430)
- Add ability to force alternative on dashboard (@ccallebs, #437)
Bugfixes:
- Fix variations reset across page loads for multiple=control and improve coverage (@Vasfed, #432)
Misc:
- Remove Explicit Return (@BradHudson, #441)
- Update Redis config docs (@bschaeffer, #422)
- Harden HTTP Basic snippet against timing attacks (@eliotsykes, #443)
- Removed a couple old ruby 1.8 hacks (@andrew, #456)
- Run tests on rails 5 (@andrew, #457)
- Fixed a few codeclimate warnings (@andrew, #458)
- Use codeclimate for test coverage (@andrew #455)
## 2.1.0 (August 8th, 2016)
Features:
- Support REDIS_PROVIDER variable used in Heroku (@kartikluke, #426)
## 2.0.0 (July 17th, 2016)
Breaking changes:
- Removed deprecated `finished` and `begin_experiment` methods
- Namespaced override param to avoid potential clashes (@henrik, #398)
## 1.7.0 (June 28th, 2016)
Features:
- Running concurrent experiments on same endpoint/view (@karmakaze, #421)
## 1.6.0 (June 16th, 2016)
Features:
- Add Dual Redis(logged-in)/cookie(logged-out) persistence adapter (@karmakaze, #420)
## 1.5.0 (June 8th, 2016)
Features:
- Add `expire_seconds:` TTL option to RedisAdapter (@karmakaze, #409)
- Optional custom persistence adapter (@ndelage, #411)
Misc:
- Use fakeredis for testing (@andrew, #412)
## 1.4.5 (June 7th, 2016)
Bugfixes:
- FIX Negative numbers on non-finished (@divineforest, #408)
- Eliminate extra RedisAdapter hget (@karmakaze, #407)
- Remove unecessary code from Experiment class (@pakallis, #391, #392, #393)
Misc:
- Simplify Configuration#normalized_experiments (@pakallis, #395)
- Clarify test running instructions (@henrik, #397)
## 1.4.4 (May 9th, 2016)
Bugfixes:
- Increment participation if store override is true and no experiment key exists (@spheric, #380)
Misc:
- Deprecated `finished` method in favour of `ab_finished` (@andreibondarev, #389)
- Added minimum version requirement to simple-random
- Clarify finished with first option being a hash in Readme (@henrik, #382)
- Refactoring the User abstraction (@andreibondarev, #384)
## 1.4.3 (April 28th, 2016)
Features:
- add on_trial callback whenever a trial is started (@mtyeh411, #375)
Bugfixes:
- Allow algorithm configuration at experiment level (@007sumit, #376)
Misc:
- only choose override if it exists as valid alternative (@spheric, #377)
## 1.4.2 (April 25th, 2016)
Misc:
- Deprecated some legacy methods (@andreibondarev, #374)
## 1.4.1 (April 21st, 2016)
Bugfixes:
- respect manual start configuration after an experiment has been deleted (@mtyeh411, #372)
Misc:
- Introduce goals collection to reduce complexity of Experiment#save (@pakallis, #365)
- Revise specs according to http://betterspecs.org/ (@hkliya, #369)
## 1.4.0 (April 2nd, 2016)
Features:
- Added experiment filters to dashboard (@ccallebs, #363, #364)
- Added Contributor Covenant Code of Conduct
## 1.3.2 (January 2nd, 2016)
Bugfixes:
- Fix deleting experiments in from the updated dashboard (@craigmcnamara, #352)
## 1.3.1 (January 1st, 2016)
Bugfixes:
- Fix the dashboard for experiments with ‘/‘ in the name. (@craigmcnamara, #349)
## 1.3.0 (October 20th, 2015)
Features:
- allow for custom redis_url different from ENV variable (@davidgrieser, #323)
- add ability to change the length of the persistence cookie (@peterylai, #335)
Bugfixes:
- Rescue from Redis::BaseError instead of Redis::CannotConnectError (@nfm, #342)
- Fix active experiments when experiment is on a later version (@ndrisso, #331)
- Fix caching of winning alternative (@nfm, #329)
Misc:
- Remove duplication from Experiment#save (@pakallis, #333)
- Remove unnecessary argument from Experiment#write_to_alternative (@t4deu, #332)
## 1.2.1 (May 17th, 2015)
Features:
- Handle redis DNS resolution failures gracefully (@fusion2004, #310)
- Push metadata to ab_test block (@ekorneeff, #296)
- Helper methods are now private when included in controllers (@ipoval, #303)
Bugfixes:
- Return an empty hash as metadata when Split is disabled (@tomasdundacek, #313)
- Don't use capture helper from ActionView (@tomasdundacek, #312)
Misc:
- Remove body "max-width" from dashboard (@xicreative, #299)
- fix private for class methods (@ipoval, #301)
- minor memoization fix in spec (@ipoval, #304)
- Minor documentation fixes (#295, #297, #305, #308)
## 1.2.0 (January 24th, 2015)
Features:
- Configure redis using environment variables if available (@saratovsource , #293)
- Store metadata on experiment configuration (@dekz, #291)
Bugfixes:
- Revert the Trial#complete! public API to support noargs (@dekz, #292)
## 1.1.0 (January 9th, 2015)
Changes:
- Public class methods on `Split::Experiment` (e.g., `find_or_create`)
have been moved to `Split::ExperimentCatalog`.
Features:
- Decouple trial from Split::Helper (@joshdover, #286)
- Helper method for Active Experiments (@blahblahblah-, #273)
Misc:
- Use the new travis container based infrastructure for tests (@andrew, #280)
## 1.0.0 (October 12th, 2014)
Changes:
- Remove support for Ruby 1.8.7 and Rails 2.3 (@qpowell, #271)
## 0.8.0 (September 25th, 2014)
Features:
- Added new way to calculate the probability an alternative is the winner (@caser, #266, #251)
- support multiple metrics per experiment (@stevenou, #260)
Bugfixes:
- Avoiding call to params in EncapsulatedHelper (@afn, #257)
## 0.7.3 (September 16th, 2014)
Features:
- Disable all split tests via a URL parameter (@hwartig, #263)
Bugfixes:
- Correctly escape experiment names on dashboard (@ecaron, #265)
- Handle redis connection exception error properly (@andrew, #245)
## 0.7.2 (June 12th, 2014)
Features:
- Show metrics on the dashboard (@swrobel, #241)
Bugfixes:
- Avoid nil error with ExperimentCatalog when upgrading (@danielschwartz, #253)
- [SECURITY ISSUE] Only allow known alternatives as query param overrides (@ankane, #255)
## 0.7.1 (March 20th, 2014)
Features:
- You can now reopen experiment from the dashboard (@mikezaby, #235)
Misc:
- Internal code tidy up (@IanVaughan, #238)
## 0.7.0 (December 26th, 2013)
Features:
- Significantly improved z-score algorithm (@caser ,#221)
- Better sorting of Experiments on dashboard (@wadako111, #218)
Bugfixes:
- Fixed start button not being displayed in some cases (@vigosan, #219)
Misc:
- Experiment#initialize refactoring (@nberger, #224)
- Extract ExperimentStore into a seperate class (@nberger, #225)
## 0.6.6 (October 15th, 2013)
Features:
- Sort experiments on Dashboard so "active" ones without a winner appear first (@swrobel, #204)
- Starting tests manually (@duksis, #209)
Bugfixes:
- Only trigger completion callback with valid Trial (@segfaultAX, #208)
- Fixed bug with `resettable` when using `normalize_experiments` (@jonashuckestein, #213)
Misc:
- Added more bots to filter list (@lbeder, #214, #215, #216)
## 0.6.5 (August 23, 2013)
Features:
- Added Redis adapter for persisting experiments across sessions (@fengb, #203)
Misc:
- Expand upon algorithms section in README (@swrobel, #200)
## 0.6.4 (August 8, 2013)
Features:
- Add hooks for experiment deletion and resetting (@craigmcnamara, #198)
- Allow Split::Helper to be used outside of a controller (@nfm, #190)
- Show current Rails/Rack Env in dashboard (@rceee, #187)
Bugfixes:
- Fix whiplash algorithm when using goals (@swrobel, #193)
Misc:
- Refactor dashboard js (@buddhamagnet)
## 0.6.3 (July 8, 2013)
Features:
- Add hooks for Trial#choose! and Trial#complete! (@bmarini, #176)
Bugfixes:
- Stores and parses Experiment's start_time as a UNIX integer (@joeroot, #177)
## 0.6.2 (June 6, 2013)
Features:
- Rails 2.3 compatibility (@bhcarpenter, #167)
- Adding possibility to store overridden alternative (@duksis, #173)
Misc:
- Now testing against multiple versions of rails
## 0.6.1 (May 4, 2013)
Bugfixes:
- Use the specified algorithm for the experiment instead of the default (@woodhull, #165)
Misc:
- Ensure experiements are valid when configuring (@ashmckenzie, #159)
- Allow arrays to be passed to ab_test (@fenelon, #156)
## 0.6.0 (April 4, 2013)
Features:
- Support for Ruby 2.0.0 (@phoet, #142)
- Multiple Goals (@liujin, #109)
- Ignoring IPs using Regular Expressions (@waynemoore, #119)
- Added ability to add more bots to the default list (@themgt, #140)
- Allow custom configuration of user blocking logic (@phoet , #148)
Bugfixes:
- Fixed regression in handling of config files (@iangreenleaf, #115)
- Fixed completion rate increases for experiments users aren't participating in (@philnash, #67)
- Handle exceptions from invalid JSON in cookies (@iangreenleaf, #126)
Misc:
- updated minimum json version requirement
- Refactor Yaml Configuration (@rtwomey, #124)
- Refactoring of Experiments (@iangreenleaf @tamird, #117 #118)
- Added more known Bots, including Pingdom, Bing, YandexBot (@julesie, @zinkkrysty, @dimko)
- Improved Readme (@iangreenleaf @phoet)
## 0.5.0 (January 28, 2013)
Features:
- Persistence Adapters: Cookies and Session (@patbenatar, #98)
- Configure experiments from a hash (@iangreenleaf, #97)
- Pluggable sampling algorithms (@woodhull, #105)
Bugfixes:
- Fixed negative number of non-finished rates (@philnash, #83)
- Fixed behaviour of finished(:reset => false) (@philnash, #88)
- Only take into consideration positive z-scores (@thomasmaas, #96)
- Amended ab_test method to raise ArgumentError if passed integers or symbols as
alternatives (@buddhamagnet, #81)
## 0.4.6 (October 28, 2012)
Features:
- General code quality improvements (@buddhamagnet, #79)
Bugfixes:
- Don't increment the experiment counter if user has finished (@dimko, #78)
- Fixed an incorrect test (@jaywengrow, #74)
## 0.4.5 (August 30, 2012)
Bugfixes:
- Fixed header gradient in FF/Opera (@philnash, #69)
- Fixed reseting of experiment in session (@apsoto, #43)
## 0.4.4 (August 9, 2012)
Features:
- Allow parameter overrides, even without Redis. (@bhcarpenter, #62)
Bugfixes:
- Fixes version number always increasing when alternatives are changed (@philnash, #63)
- updated guard-rspec to version 1.2
## 0.4.3 (July 8, 2012)
Features:
- redis failover now recovers from all redis-related exceptions
## 0.4.2 (June 1, 2012)
Features:
- Now works with v3.0 of redis gem
Bugfixes:
- Fixed redis failover on Rubinius
## 0.4.1 (April 6, 2012)
Features:
- Added configuration option to disable Split testing (@ilyakatz, #45)
Bugfixes:
- Fix weights for existing experiments (@andreas, #40)
- Fixed dashboard range error (@andrew, #42)
## 0.4.0 (March 7, 2012)
**IMPORTANT**
If using ruby 1.8.x and weighted alternatives you should always pass the control alternative through as the second argument with any other alternatives as a third argument because the order of the hash is not preserved in ruby 1.8, ruby 1.9 users are not affected by this bug.
Features:
- Experiments now record when they were started (@vrish88, #35)
- Old versions of experiments in sessions are now cleaned up
- Avoid users participating in multiple experiments at once (#21)
Bugfixes:
- Overriding alternatives doesn't work for weighted alternatives (@layflags, #34)
- confidence_level helper should handle tiny z-scores (#23)
## 0.3.3 (February 16, 2012)
Bugfixes:
- Fixed redis failover when a block was passed to ab_test (@layflags, #33)
## 0.3.2 (February 12, 2012)
Features:
- Handle redis errors gracefully (@layflags, #32)
## 0.3.1 (November 19, 2011)
Features:
- General code tidy up (@ryanlecompte, #22, @mocoso, #28)
- Lazy loading data from Redis (@lautis, #25)
Bugfixes:
- Handle unstarted experiments (@mocoso, #27)
- Relaxed Sinatra version requirement (@martinclu, #24)
## 0.3.0 (October 9, 2011)
Features:
- Redesigned dashboard (@mrappleton, #17)
- Use atomic increments in redis for better concurrency (@lautis, #18)
- Weighted alternatives
Bugfixes:
- Fix to allow overriding of experiments that aren't on version 1
## 0.2.4 (July 18, 2011)
Features:
- Added option to finished to not reset the users session
Bugfixes:
- Only allow strings as alternatives, fixes strange errors when passing true/false or symbols
## 0.2.3 (June 26, 2011)
Features:
- Experiments can now be deleted from the dashboard
- ab_test helper now accepts a block
- Improved dashboard
Bugfixes:
- After resetting an experiment, existing users of that experiment will also be reset
## 0.2.2 (June 11, 2011)
Features:
- Updated redis-namespace requirement to 1.0.3
- Added a configuration object for changing options
- Robot regex can now be changed via a configuration options
- Added ability to ignore visits from specified IP addresses
- Dashboard now shows percentage improvement of alternatives compared to the control
- If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives
Bugfixes:
- Saving an experiment multiple times no longer creates duplicate alternatives
## 0.2.1 (May 29, 2011)
Bugfixes:
- Convert legacy sets to lists to avoid exceptions during upgrades from 0.1.x
## 0.2.0 (May 29, 2011)
Features:
- Override an alternative via a url parameter
- Experiments can now be reset from the dashboard
- The first alternative is now considered the control
- General dashboard usability improvements
- Robots are ignored and given the control alternative
Bugfixes:
- Alternatives are now store in a list rather than a set to ensure consistent ordering
- Fixed diving by zero errors
## 0.1.1 (May 18, 2011)
Bugfixes:
- More Robust conversion rate display on dashboard
- Ensure `Split::Version` is available everywhere, fixed dashboard
## 0.1.0 (May 17, 2011)
Initial Release
<MSG> update changelog
<DFF> @@ -17,6 +17,9 @@ Misc:
- Drop support for Rails < 5 (@andrehkr, #607)
- Bump minimum required redis to 4.2 (@andrehjr, #628)
- Removed repeated loading from config (@robin-phung, #619)
+- Simplify RedisInterface usage when persisting Experiment alternatives (@andrehjr, #632)
+- Remove redis_url impl. Deprecated on version 2.2 (@andrehjr, #631)
+- Remove thread_safe config as redis-rb is thread_safe by default (@andrehjr, #630)
## 3.4.1 (November 12th, 2019)
| 3 | update changelog | 0 | .md | md | mit | splitrb/split |
10071421 | <NME> CHANGELOG.md
<BEF> ## 4.0.1 (December 30th, 2021)
Bugfixes:
- ab_test must return metadata on error or if split is disabled/excluded user (@andrehjr, #622)
- Fix versioned experiments when used with allow_multiple_experiments=control (@andrehjr, #613)
- Only block Pinterest bot (@huoxito, #606)
- Respect experiment defaults when loading experiments in initializer. (@mattwd7, #599)
- Removes metadata key when it updated to nil (@andrehjr, #633)
- Force experiment does not count for metrics (@andrehjr, #637)
- Fix cleanup_old_versions! misbehaviour (@serggl, #661)
Features:
- Make goals accessible via on_trial_complete callbacks (@robin-phung, #625)
- Replace usage of SimpleRandom with RubyStats(Used for Beta Distribution RNG) (@andrehjr, #616)
- Introduce enable/disable experiment cohorting (@robin-phung, #615)
- Add on_experiment_winner_choose callback (@GenaMinenkov, #574)
- Drop support for Rails < 5 (@andrehkr, #607)
- Bump minimum required redis to 4.2 (@andrehjr, #628)
- Removed repeated loading from config (@robin-phung, #619)
## 3.4.1 (November 12th, 2019)
- Simplify RedisInterface usage when persisting Experiment alternatives (@andrehjr, #632)
- Remove redis_url impl. Deprecated on version 2.2 (@andrehjr, #631)
- Remove thread_safe config as redis-rb is thread_safe by default (@andrehjr, #630)
- Fix typo of in `Split::Trial` class variable (TomasBarry, #644)
- Single HSET to update values, instead of multiple ones (@andrehjr, #640)
- Use Redis#hmset to keep compatibility with Redis < 4.0 (@andrehjr, #659)
- Remove 'set' parsing for alternatives. Sets were used as storage and deprecated on 0.x (@andrehjr, #639)
- Adding documentation related to what is stored on cookies. (@andrehjr, #634)
- Keep railtie defined under the Split gem namespace (@avit, #666)
- Update RSpec helper to support block syntax (@clowder, #665)
## 3.4.1 (November 12th, 2019)
Bugfixes:
- Reference ActionController directly when including split helpers, to avoid breaking Rails API Controllers (@andrehjr, #602)
## 3.4.0 (November 9th, 2019)
Features:
- Improve DualAdapter (@santib, #588), adds a new configuration for the DualAdapter, making it possible to keep consistency for logged_out/logged_in users. It's a opt-in flag. No Behavior was changed on this release.
- Make dashboard pagination default "per" param configurable (@alopatin, #597)
Bugfixes:
- Fix `force_alternative` for experiments with incremented version (@giraffate, #568)
- Persist alternative weights (@giraffate, #570)
- Combined experiment performance improvements (@gnanou, #575)
- Handle correctly case when ab_finished is called before ab_test for a user (@gnanou, #577)
- When loading active_experiments, it should not look into user's 'finished' keys (@andrehjr, #582)
Misc:
- Remove `rubyforge_project` from gemspec (@giraffate, #583)
- Fix URLs to replace http with https (@giraffate , #584)
- Lazily include split helpers in ActionController::Base (@hasghari, #586)
- Fix unused variable warnings (@andrehjr, #592)
- Fix ruby warnings (@andrehjr, #593)
- Update rubocop.yml config (@andrehjr, #594)
- Add frozen_string_literal to all files that were missing it (@andrehjr, #595)
## 3.3.2 (April 12th, 2019)
Features:
- Added uptime robot to configuration.rb (@razel1982, #556)
- Check to see if being run in Rails application and run in before_initialize (@husteadrobert, #555)
Bugfixes:
- Fix error message interpolation (@hanibash, #553)
- Fix Bigdecimal warnings (@agraves, #551)
- Avoid hitting up on redis for robots/excluded users. (@andrehjr, #544)
- Checks for defined?(request) on Helper#exclude_visitor?. (@andrehjr)
Misc:
- Update travis to add Rails 6 (@edmilton, #559)
- Fix broken specs in developement environment (@dougpetronilio, #557)
## 3.3.1 (January 11th, 2019)
Features:
- Filter some more bots (@janosch-x, #542)
Bugfixes:
- Fix Dashboard Pagination Helper typo (@cattekin, #541)
- Do not storage alternative in cookie if experiment has a winner (@sadhu89, #539)
- fix user participating alternative not found (@NaturalHokke, #536)
Misc:
- Tweak RSpec instructions (@eliotsykes, #540)
- Improve README regarding rspec usage (@vermaxik, #538)
## 3.3.0 (August 13th, 2018)
Features:
- Added pagination for dashboard (@GeorgeGorbanev, #518)
- Add Facebot crawler to list of bots (@pfeiffer, #530)
- Ignore previewing requests (@pfeiffer, #531)
- Fix binding of ignore_filter (@pfeiffer, #533)
Bugfixes:
- Fix cookie header duplication (@andrehjr, #522)
Performance:
- Improve performance of RedisInterface#make_list_length by using LTRIM command (@mlovic, #509)
Misc:
- Update development dependencies
- test rails 5.2 on travis (@lostapathy, #524)
- update ruby versions for travis (@lostapathy, #525)
## 3.2.0 (September 21st, 2017)
Features:
- Allow configuration of how often winning alternatives are recalculated (@patbl, #501)
Bugfixes:
- Avoid z_score numeric exception for conversion rates >1 (@cmantas, #503)
- Fix combined experiments (@semanticart, #502)
## 3.1.1 (August 30th, 2017)
Bugfixes:
- Bring back support for ruby 1.9.3 and greater (rubygems 2.0.0 or greater now required) (@patbl, #498)
Misc:
- Document testing with RSpec (@eliotsykes, #495)
## 3.1.0 (August 14th, 2017)
Features:
- Support for combined experiments (@daviddening, #493)
- Rewrite CookieAdapter to work with Rack::Request and Rack::Response directly (@andrehjr, #490)
- Enumeration of a User's Experiments that Respects the db_failover Option(@MarkRoddy, #487)
Bugfixes:
- Blocked a few more common bot user agents (@kylerippey, #485)
Misc:
- Repository Audit by Maintainer.io (@RichardLitt, #484)
- Update development dependencies
- Test on ruby 2.4.1
- Test compatibility with rails 5.1
- Add uris to metadata section in gemspec
## 3.0.0 (March 30th, 2017)
Features:
- added block randomization algorithm and specs (@hulleywood, #475)
- Add ab_record_extra_info to allow record extra info to alternative and display on dashboard. (@tranngocsam, #460)
Bugfixes:
- Avoid crashing on Ruby 2.4 for numeric strings (@flori, #470)
- Fix issue where redis isn't required (@tomciopp , #466)
Misc:
- Avoid variable_size_secure_compare private method (@eliotsykes, #465)
## 2.2.0 (November 11th, 2016)
**Backwards incompatible!** Redis keys are renamed. Please make sure all running tests are completed before you upgrade, as they will reset.
Features:
- Remove dependency on Redis::Namespace (@bschaeffer, #425)
- Make resetting on experiment change optional (@moggyboy, #430)
- Add ability to force alternative on dashboard (@ccallebs, #437)
Bugfixes:
- Fix variations reset across page loads for multiple=control and improve coverage (@Vasfed, #432)
Misc:
- Remove Explicit Return (@BradHudson, #441)
- Update Redis config docs (@bschaeffer, #422)
- Harden HTTP Basic snippet against timing attacks (@eliotsykes, #443)
- Removed a couple old ruby 1.8 hacks (@andrew, #456)
- Run tests on rails 5 (@andrew, #457)
- Fixed a few codeclimate warnings (@andrew, #458)
- Use codeclimate for test coverage (@andrew #455)
## 2.1.0 (August 8th, 2016)
Features:
- Support REDIS_PROVIDER variable used in Heroku (@kartikluke, #426)
## 2.0.0 (July 17th, 2016)
Breaking changes:
- Removed deprecated `finished` and `begin_experiment` methods
- Namespaced override param to avoid potential clashes (@henrik, #398)
## 1.7.0 (June 28th, 2016)
Features:
- Running concurrent experiments on same endpoint/view (@karmakaze, #421)
## 1.6.0 (June 16th, 2016)
Features:
- Add Dual Redis(logged-in)/cookie(logged-out) persistence adapter (@karmakaze, #420)
## 1.5.0 (June 8th, 2016)
Features:
- Add `expire_seconds:` TTL option to RedisAdapter (@karmakaze, #409)
- Optional custom persistence adapter (@ndelage, #411)
Misc:
- Use fakeredis for testing (@andrew, #412)
## 1.4.5 (June 7th, 2016)
Bugfixes:
- FIX Negative numbers on non-finished (@divineforest, #408)
- Eliminate extra RedisAdapter hget (@karmakaze, #407)
- Remove unecessary code from Experiment class (@pakallis, #391, #392, #393)
Misc:
- Simplify Configuration#normalized_experiments (@pakallis, #395)
- Clarify test running instructions (@henrik, #397)
## 1.4.4 (May 9th, 2016)
Bugfixes:
- Increment participation if store override is true and no experiment key exists (@spheric, #380)
Misc:
- Deprecated `finished` method in favour of `ab_finished` (@andreibondarev, #389)
- Added minimum version requirement to simple-random
- Clarify finished with first option being a hash in Readme (@henrik, #382)
- Refactoring the User abstraction (@andreibondarev, #384)
## 1.4.3 (April 28th, 2016)
Features:
- add on_trial callback whenever a trial is started (@mtyeh411, #375)
Bugfixes:
- Allow algorithm configuration at experiment level (@007sumit, #376)
Misc:
- only choose override if it exists as valid alternative (@spheric, #377)
## 1.4.2 (April 25th, 2016)
Misc:
- Deprecated some legacy methods (@andreibondarev, #374)
## 1.4.1 (April 21st, 2016)
Bugfixes:
- respect manual start configuration after an experiment has been deleted (@mtyeh411, #372)
Misc:
- Introduce goals collection to reduce complexity of Experiment#save (@pakallis, #365)
- Revise specs according to http://betterspecs.org/ (@hkliya, #369)
## 1.4.0 (April 2nd, 2016)
Features:
- Added experiment filters to dashboard (@ccallebs, #363, #364)
- Added Contributor Covenant Code of Conduct
## 1.3.2 (January 2nd, 2016)
Bugfixes:
- Fix deleting experiments in from the updated dashboard (@craigmcnamara, #352)
## 1.3.1 (January 1st, 2016)
Bugfixes:
- Fix the dashboard for experiments with ‘/‘ in the name. (@craigmcnamara, #349)
## 1.3.0 (October 20th, 2015)
Features:
- allow for custom redis_url different from ENV variable (@davidgrieser, #323)
- add ability to change the length of the persistence cookie (@peterylai, #335)
Bugfixes:
- Rescue from Redis::BaseError instead of Redis::CannotConnectError (@nfm, #342)
- Fix active experiments when experiment is on a later version (@ndrisso, #331)
- Fix caching of winning alternative (@nfm, #329)
Misc:
- Remove duplication from Experiment#save (@pakallis, #333)
- Remove unnecessary argument from Experiment#write_to_alternative (@t4deu, #332)
## 1.2.1 (May 17th, 2015)
Features:
- Handle redis DNS resolution failures gracefully (@fusion2004, #310)
- Push metadata to ab_test block (@ekorneeff, #296)
- Helper methods are now private when included in controllers (@ipoval, #303)
Bugfixes:
- Return an empty hash as metadata when Split is disabled (@tomasdundacek, #313)
- Don't use capture helper from ActionView (@tomasdundacek, #312)
Misc:
- Remove body "max-width" from dashboard (@xicreative, #299)
- fix private for class methods (@ipoval, #301)
- minor memoization fix in spec (@ipoval, #304)
- Minor documentation fixes (#295, #297, #305, #308)
## 1.2.0 (January 24th, 2015)
Features:
- Configure redis using environment variables if available (@saratovsource , #293)
- Store metadata on experiment configuration (@dekz, #291)
Bugfixes:
- Revert the Trial#complete! public API to support noargs (@dekz, #292)
## 1.1.0 (January 9th, 2015)
Changes:
- Public class methods on `Split::Experiment` (e.g., `find_or_create`)
have been moved to `Split::ExperimentCatalog`.
Features:
- Decouple trial from Split::Helper (@joshdover, #286)
- Helper method for Active Experiments (@blahblahblah-, #273)
Misc:
- Use the new travis container based infrastructure for tests (@andrew, #280)
## 1.0.0 (October 12th, 2014)
Changes:
- Remove support for Ruby 1.8.7 and Rails 2.3 (@qpowell, #271)
## 0.8.0 (September 25th, 2014)
Features:
- Added new way to calculate the probability an alternative is the winner (@caser, #266, #251)
- support multiple metrics per experiment (@stevenou, #260)
Bugfixes:
- Avoiding call to params in EncapsulatedHelper (@afn, #257)
## 0.7.3 (September 16th, 2014)
Features:
- Disable all split tests via a URL parameter (@hwartig, #263)
Bugfixes:
- Correctly escape experiment names on dashboard (@ecaron, #265)
- Handle redis connection exception error properly (@andrew, #245)
## 0.7.2 (June 12th, 2014)
Features:
- Show metrics on the dashboard (@swrobel, #241)
Bugfixes:
- Avoid nil error with ExperimentCatalog when upgrading (@danielschwartz, #253)
- [SECURITY ISSUE] Only allow known alternatives as query param overrides (@ankane, #255)
## 0.7.1 (March 20th, 2014)
Features:
- You can now reopen experiment from the dashboard (@mikezaby, #235)
Misc:
- Internal code tidy up (@IanVaughan, #238)
## 0.7.0 (December 26th, 2013)
Features:
- Significantly improved z-score algorithm (@caser ,#221)
- Better sorting of Experiments on dashboard (@wadako111, #218)
Bugfixes:
- Fixed start button not being displayed in some cases (@vigosan, #219)
Misc:
- Experiment#initialize refactoring (@nberger, #224)
- Extract ExperimentStore into a seperate class (@nberger, #225)
## 0.6.6 (October 15th, 2013)
Features:
- Sort experiments on Dashboard so "active" ones without a winner appear first (@swrobel, #204)
- Starting tests manually (@duksis, #209)
Bugfixes:
- Only trigger completion callback with valid Trial (@segfaultAX, #208)
- Fixed bug with `resettable` when using `normalize_experiments` (@jonashuckestein, #213)
Misc:
- Added more bots to filter list (@lbeder, #214, #215, #216)
## 0.6.5 (August 23, 2013)
Features:
- Added Redis adapter for persisting experiments across sessions (@fengb, #203)
Misc:
- Expand upon algorithms section in README (@swrobel, #200)
## 0.6.4 (August 8, 2013)
Features:
- Add hooks for experiment deletion and resetting (@craigmcnamara, #198)
- Allow Split::Helper to be used outside of a controller (@nfm, #190)
- Show current Rails/Rack Env in dashboard (@rceee, #187)
Bugfixes:
- Fix whiplash algorithm when using goals (@swrobel, #193)
Misc:
- Refactor dashboard js (@buddhamagnet)
## 0.6.3 (July 8, 2013)
Features:
- Add hooks for Trial#choose! and Trial#complete! (@bmarini, #176)
Bugfixes:
- Stores and parses Experiment's start_time as a UNIX integer (@joeroot, #177)
## 0.6.2 (June 6, 2013)
Features:
- Rails 2.3 compatibility (@bhcarpenter, #167)
- Adding possibility to store overridden alternative (@duksis, #173)
Misc:
- Now testing against multiple versions of rails
## 0.6.1 (May 4, 2013)
Bugfixes:
- Use the specified algorithm for the experiment instead of the default (@woodhull, #165)
Misc:
- Ensure experiements are valid when configuring (@ashmckenzie, #159)
- Allow arrays to be passed to ab_test (@fenelon, #156)
## 0.6.0 (April 4, 2013)
Features:
- Support for Ruby 2.0.0 (@phoet, #142)
- Multiple Goals (@liujin, #109)
- Ignoring IPs using Regular Expressions (@waynemoore, #119)
- Added ability to add more bots to the default list (@themgt, #140)
- Allow custom configuration of user blocking logic (@phoet , #148)
Bugfixes:
- Fixed regression in handling of config files (@iangreenleaf, #115)
- Fixed completion rate increases for experiments users aren't participating in (@philnash, #67)
- Handle exceptions from invalid JSON in cookies (@iangreenleaf, #126)
Misc:
- updated minimum json version requirement
- Refactor Yaml Configuration (@rtwomey, #124)
- Refactoring of Experiments (@iangreenleaf @tamird, #117 #118)
- Added more known Bots, including Pingdom, Bing, YandexBot (@julesie, @zinkkrysty, @dimko)
- Improved Readme (@iangreenleaf @phoet)
## 0.5.0 (January 28, 2013)
Features:
- Persistence Adapters: Cookies and Session (@patbenatar, #98)
- Configure experiments from a hash (@iangreenleaf, #97)
- Pluggable sampling algorithms (@woodhull, #105)
Bugfixes:
- Fixed negative number of non-finished rates (@philnash, #83)
- Fixed behaviour of finished(:reset => false) (@philnash, #88)
- Only take into consideration positive z-scores (@thomasmaas, #96)
- Amended ab_test method to raise ArgumentError if passed integers or symbols as
alternatives (@buddhamagnet, #81)
## 0.4.6 (October 28, 2012)
Features:
- General code quality improvements (@buddhamagnet, #79)
Bugfixes:
- Don't increment the experiment counter if user has finished (@dimko, #78)
- Fixed an incorrect test (@jaywengrow, #74)
## 0.4.5 (August 30, 2012)
Bugfixes:
- Fixed header gradient in FF/Opera (@philnash, #69)
- Fixed reseting of experiment in session (@apsoto, #43)
## 0.4.4 (August 9, 2012)
Features:
- Allow parameter overrides, even without Redis. (@bhcarpenter, #62)
Bugfixes:
- Fixes version number always increasing when alternatives are changed (@philnash, #63)
- updated guard-rspec to version 1.2
## 0.4.3 (July 8, 2012)
Features:
- redis failover now recovers from all redis-related exceptions
## 0.4.2 (June 1, 2012)
Features:
- Now works with v3.0 of redis gem
Bugfixes:
- Fixed redis failover on Rubinius
## 0.4.1 (April 6, 2012)
Features:
- Added configuration option to disable Split testing (@ilyakatz, #45)
Bugfixes:
- Fix weights for existing experiments (@andreas, #40)
- Fixed dashboard range error (@andrew, #42)
## 0.4.0 (March 7, 2012)
**IMPORTANT**
If using ruby 1.8.x and weighted alternatives you should always pass the control alternative through as the second argument with any other alternatives as a third argument because the order of the hash is not preserved in ruby 1.8, ruby 1.9 users are not affected by this bug.
Features:
- Experiments now record when they were started (@vrish88, #35)
- Old versions of experiments in sessions are now cleaned up
- Avoid users participating in multiple experiments at once (#21)
Bugfixes:
- Overriding alternatives doesn't work for weighted alternatives (@layflags, #34)
- confidence_level helper should handle tiny z-scores (#23)
## 0.3.3 (February 16, 2012)
Bugfixes:
- Fixed redis failover when a block was passed to ab_test (@layflags, #33)
## 0.3.2 (February 12, 2012)
Features:
- Handle redis errors gracefully (@layflags, #32)
## 0.3.1 (November 19, 2011)
Features:
- General code tidy up (@ryanlecompte, #22, @mocoso, #28)
- Lazy loading data from Redis (@lautis, #25)
Bugfixes:
- Handle unstarted experiments (@mocoso, #27)
- Relaxed Sinatra version requirement (@martinclu, #24)
## 0.3.0 (October 9, 2011)
Features:
- Redesigned dashboard (@mrappleton, #17)
- Use atomic increments in redis for better concurrency (@lautis, #18)
- Weighted alternatives
Bugfixes:
- Fix to allow overriding of experiments that aren't on version 1
## 0.2.4 (July 18, 2011)
Features:
- Added option to finished to not reset the users session
Bugfixes:
- Only allow strings as alternatives, fixes strange errors when passing true/false or symbols
## 0.2.3 (June 26, 2011)
Features:
- Experiments can now be deleted from the dashboard
- ab_test helper now accepts a block
- Improved dashboard
Bugfixes:
- After resetting an experiment, existing users of that experiment will also be reset
## 0.2.2 (June 11, 2011)
Features:
- Updated redis-namespace requirement to 1.0.3
- Added a configuration object for changing options
- Robot regex can now be changed via a configuration options
- Added ability to ignore visits from specified IP addresses
- Dashboard now shows percentage improvement of alternatives compared to the control
- If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives
Bugfixes:
- Saving an experiment multiple times no longer creates duplicate alternatives
## 0.2.1 (May 29, 2011)
Bugfixes:
- Convert legacy sets to lists to avoid exceptions during upgrades from 0.1.x
## 0.2.0 (May 29, 2011)
Features:
- Override an alternative via a url parameter
- Experiments can now be reset from the dashboard
- The first alternative is now considered the control
- General dashboard usability improvements
- Robots are ignored and given the control alternative
Bugfixes:
- Alternatives are now store in a list rather than a set to ensure consistent ordering
- Fixed diving by zero errors
## 0.1.1 (May 18, 2011)
Bugfixes:
- More Robust conversion rate display on dashboard
- Ensure `Split::Version` is available everywhere, fixed dashboard
## 0.1.0 (May 17, 2011)
Initial Release
<MSG> update changelog
<DFF> @@ -17,6 +17,9 @@ Misc:
- Drop support for Rails < 5 (@andrehkr, #607)
- Bump minimum required redis to 4.2 (@andrehjr, #628)
- Removed repeated loading from config (@robin-phung, #619)
+- Simplify RedisInterface usage when persisting Experiment alternatives (@andrehjr, #632)
+- Remove redis_url impl. Deprecated on version 2.2 (@andrehjr, #631)
+- Remove thread_safe config as redis-rb is thread_safe by default (@andrehjr, #630)
## 3.4.1 (November 12th, 2019)
| 3 | update changelog | 0 | .md | md | mit | splitrb/split |
10071422 | <NME> TODO
<BEF> * Write a tutorial on how to set up the server, registering projects, and
how to upload releases.
* Make it possible to register users via distutils.
(There should be a setting to turn this feature on/off).
There should be a setting to turn this feature on/off for private PyPIs.
[taken-by: sverrej]
* Maybe add a permission "can upload new release", so more than one
user can change the same project.
* Should a project have co-owners?
- One possible solution:
http://github.com/initcrash/django-object-permissions/tree
* Script to populate classifiers from
http://pypi.python.org/pypi?%3Aaction=list_classifiers
* Package author admin interface (submit, edit, view)
* Documentation upload
* Ratings
* Random Monty Python quotes :-)
* Comments :-)
Post-PyPI
=========
* PEP-381: Mirroring infrastructure for PyPI
[taken-by: jezdez]
* API to submit test reports for smoke test bots. Like CPAN Testers.
Platform/version/matrix etc.
* Different listings: Author listings, classifier listings, etc.
* Search metadata
* Automatic generation of Sphinx for modules (so you can view them directly
on pypi, like CPAN), Module listing etc.
* Listing of special files: README, LICENSE, Changefile/Changes, TODO,
MANIFEST.
* Dependency graphs.
* Package file browser (like CPAN)
Documentation
=============
* Write a tutorial on how to set up the server, registering projects, and
how to upload releases.
<MSG> Removed done todo item
<DFF> @@ -1,4 +1,4 @@
-* Write a tutorial on how to set up the server, registering projects, and
+* Write a tutorial on how to set up the server, registering projects, and
how to upload releases.
* Make it possible to register users via distutils.
(There should be a setting to turn this feature on/off).
@@ -7,7 +7,6 @@
* Maybe add a permission "can upload new release", so more than one
user can change the same project.
* Should a project have co-owners?
- - One possible solution:
+ - One possible solution:
http://github.com/initcrash/django-object-permissions/tree
-* Script to populate classifiers from
- http://pypi.python.org/pypi?%3Aaction=list_classifiers
+
| 3 | Removed done todo item | 4 | TODO | bsd-3-clause | ask/chishop |
|
10071423 | <NME> stylesheet.ts
<BEF> ADDFILE
<MSG> Working implementation of CSS snippets resolver
<DFF> @@ -0,0 +1,50 @@
+import { strictEqual as equal } from 'assert';
+import { stylesheet as expandAbbreviation, parseStylesheetSnippets, resolveConfig } from '../src';
+
+const defaultConfig = resolveConfig({
+ type: 'stylesheet',
+ options: {
+ 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`
+ }
+});
+const snippets = parseStylesheetSnippets(defaultConfig.snippets);
+
+function expand(abbr: string, config = defaultConfig) {
+ return expandAbbreviation(abbr, config, snippets);
+}
+
+describe('Stylesheet', () => {
+ describe('Snippet resolver', () => {
+ it('keywords', () => {
+ equal(expand('bd1-s'), 'border: 1px solid;');
+ equal(expand('dib'), 'display: inline-block;');
+ equal(expand('bxsz'), 'box-sizing: ${1:border-box};');
+ equal(expand('bxz'), 'box-sizing: ${1:border-box};');
+ equal(expand('bxzc'), 'box-sizing: content-box;');
+ equal(expand('fl'), 'float: ${1:left};');
+ equal(expand('fll'), 'float: left;');
+
+ equal(expand('pos'), 'position: ${1:relative};');
+ equal(expand('poa'), 'position: absolute;');
+ equal(expand('por'), 'position: relative;');
+ equal(expand('pof'), 'position: fixed;');
+ equal(expand('pos-a'), 'position: absolute;');
+
+ equal(expand('m'), 'margin: ${0};');
+ equal(expand('m0'), 'margin: 0;');
+
+ // use `auto` as global keyword
+ equal(expand('m0-a'), 'margin: 0 auto;');
+ equal(expand('m-a'), 'margin: auto;');
+
+ equal(expand('bg'), 'background: ${1:#000};');
+
+ equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};');
+ equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;');
+ equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;');
+ equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;');
+
+ equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});');
+ });
+ });
+});
| 50 | Working implementation of CSS snippets resolver | 0 | .ts | ts | mit | emmetio/emmet |
10071424 | <NME> stylesheet.ts
<BEF> ADDFILE
<MSG> Working implementation of CSS snippets resolver
<DFF> @@ -0,0 +1,50 @@
+import { strictEqual as equal } from 'assert';
+import { stylesheet as expandAbbreviation, parseStylesheetSnippets, resolveConfig } from '../src';
+
+const defaultConfig = resolveConfig({
+ type: 'stylesheet',
+ options: {
+ 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`
+ }
+});
+const snippets = parseStylesheetSnippets(defaultConfig.snippets);
+
+function expand(abbr: string, config = defaultConfig) {
+ return expandAbbreviation(abbr, config, snippets);
+}
+
+describe('Stylesheet', () => {
+ describe('Snippet resolver', () => {
+ it('keywords', () => {
+ equal(expand('bd1-s'), 'border: 1px solid;');
+ equal(expand('dib'), 'display: inline-block;');
+ equal(expand('bxsz'), 'box-sizing: ${1:border-box};');
+ equal(expand('bxz'), 'box-sizing: ${1:border-box};');
+ equal(expand('bxzc'), 'box-sizing: content-box;');
+ equal(expand('fl'), 'float: ${1:left};');
+ equal(expand('fll'), 'float: left;');
+
+ equal(expand('pos'), 'position: ${1:relative};');
+ equal(expand('poa'), 'position: absolute;');
+ equal(expand('por'), 'position: relative;');
+ equal(expand('pof'), 'position: fixed;');
+ equal(expand('pos-a'), 'position: absolute;');
+
+ equal(expand('m'), 'margin: ${0};');
+ equal(expand('m0'), 'margin: 0;');
+
+ // use `auto` as global keyword
+ equal(expand('m0-a'), 'margin: 0 auto;');
+ equal(expand('m-a'), 'margin: auto;');
+
+ equal(expand('bg'), 'background: ${1:#000};');
+
+ equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};');
+ equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;');
+ equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;');
+ equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;');
+
+ equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});');
+ });
+ });
+});
| 50 | Working implementation of CSS snippets resolver | 0 | .ts | ts | mit | emmetio/emmet |
10071425 | <NME> transducers.js
<BEF> var transducers =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
// basic protocol helpers
var symbolExists = typeof Symbol !== 'undefined';
var protocols = {
iterator: symbolExists ? Symbol.iterator : '@@iterator',
transformer: symbolExists ? Symbol('transformer') : '@@transformer'
};
function throwProtocolError(name, coll) {
throw new Error("don't know how to " + name + " collection: " +
coll);
}
function fulfillsProtocol(obj, name) {
if(name === 'iterator') {
// Accept ill-formed iterators that don't conform to the
// protocol by accepting just next()
return obj[protocols.iterator] || obj.next;
}
return obj[protocols[name]];
}
function getProtocolProperty(obj, name) {
return obj[protocols[name]];
}
function iterator(coll) {
var iter = getProtocolProperty(coll, 'iterator');
if(iter) {
return iter.call(coll);
}
else if(coll.next) {
// Basic duck typing to accept an ill-formed iterator that doesn't
// conform to the iterator protocol (all iterators should have the
// @@iterator method and return themselves, but some engines don't
// have that on generators like older v8)
return coll;
}
else if(isArray(coll)) {
return new ArrayIterator(coll);
}
else if(isObject(coll)) {
return new ObjectIterator(coll);
}
}
function ArrayIterator(arr) {
this.arr = arr;
this.index = 0;
}
ArrayIterator.prototype.next = function() {
if(this.index < this.arr.length) {
return {
value: this.arr[this.index++],
done: false
};
}
return {
done: true
}
};
function ObjectIterator(obj) {
this.obj = obj;
this.keys = Object.keys(obj);
this.index = 0;
}
ObjectIterator.prototype.next = function() {
if(this.index < this.keys.length) {
var k = this.keys[this.index++];
return {
value: [k, this.obj[k]],
done: false
};
}
return {
done: true
}
};
// helpers
function isArray(x) {
return x instanceof Array;
}
var toString = Object.prototype.toString;
var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) {
return toString.call(obj) == '[object Array]';
};
function isFunction(x) {
return typeof x === 'function';
}
function isObject(x) {
return x instanceof Object &&
Object.getPrototypeOf(x) === Object.getPrototypeOf({});
}
function isNumber(x) {
return typeof x === 'number';
}
function Reduced(value) {
this.__transducers_reduced__ = true;
this.value = value;
}
function isReduced(x) {
return (x instanceof Reduced) || (x && x.__transducers_reduced__);
}
function deref(x) {
return x.value;
}
/**
* This is for transforms that may call their nested transforms before
* Reduced-wrapping the result (e.g. "take"), to avoid nested Reduced.
*/
function ensureReduced(val) {
if(isReduced(val)) {
return val;
} else {
return new Reduced(val);
}
}
/**
* This is for tranforms that call their nested transforms when
* performing completion (like "partition"), to avoid signaling
* termination after already completing.
*/
function ensureUnreduced(v) {
if(isReduced(v)) {
return deref(v);
} else {
return v;
}
}
function reduce(coll, xform, init) {
if(isArray(coll)) {
var result = init;
var index = -1;
var len = coll.length;
while(++index < len) {
result = xform.step(result, coll[index]);
if(isReduced(result)) {
result = deref(result);
break;
}
}
return xform.result(result);
// transformations
function reducer(f) {
return {
init: function() {
throw new Error('init value unavailable');
if(isReduced(result)) {
result = deref(result);
break;
}
val = iter.next();
}
return xform.result(result);
}
throwProtocolError('iterate', coll);
}
function transduce(coll, xform, reducer, init) {
xform = xform(reducer);
if(init === undefined) {
init = xform.init();
}
return reduce(coll, xform, init);
}
function compose() {
var funcs = Array.prototype.slice.call(arguments);
return function(r) {
var value = r;
for(var i=funcs.length-1; i>=0; i--) {
value = funcs[i](value);
}
return value;
}
}
// transformations
function transformer(f) {
return {
init: function() {
throw new Error('init value unavailable');
},
result: function(v) {
return v;
},
step: f
};
}
function bound(f, ctx, count) {
count = count != null ? count : 1;
if(!ctx) {
return f;
}
else {
switch(count) {
case 1:
return function(x) {
return f.call(ctx, x);
}
case 2:
return function(x, y) {
return f.call(ctx, x, y);
}
default:
return f.bind(ctx);
}
}
}
function arrayMap(arr, f, ctx) {
var index = -1;
var length = arr.length;
var result = Array(length);
f = bound(f, ctx, 2);
while (++index < length) {
result[index] = f(arr[index], index);
}
return result;
}
function arrayFilter(arr, f, ctx) {
var len = arr.length;
var result = [];
f = bound(f, ctx, 2);
for(var i=0; i<len; i++) {
if(f(arr[i], i)) {
result.push(arr[i]);
}
}
return result;
}
function Map(f, xform) {
this.xform = xform;
this.f = f;
}
Map.prototype.init = function() {
return this.xform.init();
};
Map.prototype.result = function(v) {
return this.xform.result(v);
};
Map.prototype.step = function(res, input) {
return this.xform.step(res, this.f(input));
};
function map(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
if(isArray(coll)) {
return arrayMap(coll, f, ctx);
}
return seq(coll, map(f));
}
return function(xform) {
return new Map(f, xform);
}
}
function Filter(f, xform) {
this.xform = xform;
this.f = f;
}
Filter.prototype.init = function() {
return this.xform.init();
};
Filter.prototype.result = function(v) {
return this.xform.result(v);
};
Filter.prototype.step = function(res, input) {
if(this.f(input)) {
return this.xform.step(res, input);
}
return res;
};
function filter(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
if(isArray(coll)) {
return arrayFilter(coll, f, ctx);
}
return seq(coll, filter(f));
}
return function(xform) {
return new Filter(f, xform);
};
}
function remove(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
return filter(coll, function(x) { return !f(x); });
}
function keep(coll) {
return filter(coll, function(x) { return x != null });
}
function Dedupe(xform) {
this.xform = xform;
this.last = undefined;
}
Dedupe.prototype.init = function() {
return this.xform.init();
};
Dedupe.prototype.result = function(v) {
return this.xform.result(v);
};
Dedupe.prototype.step = function(result, input) {
if(input !== this.last) {
this.last = input;
return this.xform.step(result, input);
}
return result;
};
function dedupe(coll) {
if(coll) {
return seq(coll, dedupe());
}
return function(xform) {
return new Dedupe(xform);
}
}
function TakeWhile(f, xform) {
this.xform = xform;
this.f = f;
}
TakeWhile.prototype.init = function() {
return this.xform.init();
};
TakeWhile.prototype.result = function(v) {
return this.xform.result(v);
};
TakeWhile.prototype.step = function(result, input) {
if(this.f(input)) {
return this.xform.step(result, input);
}
return new Reduced(result);
};
function takeWhile(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
return seq(coll, takeWhile(f));
}
return function(xform) {
return new TakeWhile(f, xform);
}
}
function Take(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
}
Take.prototype.init = function() {
return this.xform.init();
};
Take.prototype.result = function(v) {
return this.xform.result(v);
};
Take.prototype.step = function(result, input) {
if (this.i < this.n) {
result = this.xform.step(result, input);
if(this.i + 1 >= this.n) {
// Finish reducing on the same step as the final value. TODO:
// double-check that this doesn't break any semantics
result = ensureReduced(result);
}
}
this.i++;
return result;
};
function take(coll, n) {
if(isNumber(coll)) { n = coll; coll = null }
if(coll) {
return seq(coll, take(n));
}
return function(xform) {
return new Take(n, xform);
}
}
function Drop(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
}
Drop.prototype.init = function() {
return this.xform.init();
};
Drop.prototype.result = function(v) {
return this.xform.result(v);
};
Drop.prototype.step = function(result, input) {
if(this.i++ < this.n) {
return result;
}
return this.xform.step(result, input);
};
function drop(coll, n) {
if(isNumber(coll)) { n = coll; coll = null }
if(coll) {
return seq(coll, drop(n));
}
return function(xform) {
return new Drop(n, xform);
}
}
function DropWhile(f, xform) {
this.xform = xform;
this.f = f;
this.dropping = true;
}
DropWhile.prototype.init = function() {
return this.xform.init();
};
DropWhile.prototype.result = function(v) {
return this.xform.result(v);
};
DropWhile.prototype.step = function(result, input) {
if(this.dropping) {
if(this.f(input)) {
return result;
}
else {
this.dropping = false;
}
}
return this.xform.step(result, input);
};
function dropWhile(coll, f, ctx) {
if(isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if(coll) {
return seq(coll, dropWhile(f));
}
return function(xform) {
return new DropWhile(f, xform);
}
}
function Partition(n, xform) {
this.n = n;
this.i = 0;
this.xform = xform;
this.part = new Array(n);
}
Partition.prototype.init = function() {
return this.xform.init();
};
Partition.prototype.result = function(v) {
if (this.i > 0) {
return ensureUnreduced(this.xform.step(v, this.part.slice(0, this.i)));
}
return this.xform.result(v);
};
Partition.prototype.step = function(result, input) {
this.part[this.i] = input;
this.i += 1;
if (this.i === this.n) {
var out = this.part.slice(0, this.n);
this.part = new Array(this.n);
this.i = 0;
return this.xform.step(result, out);
}
return result;
};
function partition(coll, n) {
if (isNumber(coll)) {
n = coll; coll = null;
}
if (coll) {
return seq(coll, partition(n));
}
return function(xform) {
return new Partition(n, xform);
};
}
var NOTHING = {};
function PartitionBy(f, xform) {
// TODO: take an "opts" object that allows the user to specify
// equality
this.f = f;
this.xform = xform;
this.part = [];
this.last = NOTHING;
}
PartitionBy.prototype.init = function() {
return this.xform.init();
};
PartitionBy.prototype.result = function(v) {
var l = this.part.length;
if (l > 0) {
return ensureUnreduced(this.xform.step(v, this.part.slice(0, l)));
}
return this.xform.result(v);
};
PartitionBy.prototype.step = function(result, input) {
var current = this.f(input);
if (current === this.last || this.last === NOTHING) {
this.part.push(input);
} else {
result = this.xform.step(result, this.part);
this.part = [input];
}
this.last = current;
return result;
};
function partitionBy(coll, f, ctx) {
if (isFunction(coll)) { ctx = f; f = coll; coll = null; }
f = bound(f, ctx);
if (coll) {
return seq(coll, partitionBy(f));
}
return function(xform) {
return new PartitionBy(f, xform);
};
}
// pure transducers (cannot take collections)
function Cat(xform) {
this.xform = xform;
}
else if(isObject(to)) {
return transduce(from, xform, objReducer, to);
}
else if(fulfillsProtocol(to, 'tranformer')) {
return transduce(from,
xform,
getProtocolProperty(to, 'transformer'),
};
Cat.prototype.step = function(result, input) {
var xform = this.xform;
var newxform = {
init: function() {
return xform.init();
},
result: function(v) {
return v;
},
step: function(result, input) {
var val = xform.step(result, input);
return isReduced(val) ? deref(val) : val;
}
}
return reduce(input, newxform, result);
};
function cat(xform) {
return new Cat(xform);
}
function mapcat(f, ctx) {
f = bound(f, ctx);
return compose(map(f), cat);
}
// collection helpers
function push(arr, x) {
arr.push(x);
return arr;
}
function merge(obj, x) {
if(isArray(x) && x.length === 2) {
obj[x[0]] = x[1];
}
this.stepper = new Stepper(xform, iterator(coll));
}
return obj;
}
var arrayReducer = {
init: function() {
return [];
},
result: function(v) {
return v;
},
step: push
}
var objReducer = {
init: function() {
return {};
},
result: function(v) {
return v;
},
step: merge
};
function getReducer(coll) {
if(isArray(coll)) {
return arrayReducer;
}
else if(isObject(coll)) {
return objReducer;
}
else if(fulfillsProtocol(coll, 'transformer')) {
return getProtocolProperty(coll, 'transformer');
}
throwProtocolError('getReducer', coll);
module.exports = {
reduce: reduce,
reducer: reducer,
Reduced: Reduced,
iterator: iterator,
push: push,
}
return transduce(coll, xform, arrayReducer, []);
}
function toObj(coll, xform) {
if(!xform) {
return reduce(coll, objReducer, {});
}
return transduce(coll, xform, objReducer, {});
}
function toIter(coll, xform) {
if(!xform) {
return iterator(coll);
}
return new LazyTransformer(xform, coll);
}
function seq(coll, xform) {
if(isArray(coll)) {
return transduce(coll, xform, arrayReducer, []);
}
else if(isObject(coll)) {
return transduce(coll, xform, objReducer, {});
}
else if(fulfillsProtocol(coll, 'transformer')) {
var transformer = getProtocolProperty(coll, 'transformer');
return transduce(coll, xform, transformer, transformer.init());
}
else if(fulfillsProtocol(coll, 'iterator')) {
return new LazyTransformer(xform, coll);
}
throwProtocolError('sequence', coll);
}
function into(to, xform, from) {
if(isArray(to)) {
return transduce(from, xform, arrayReducer, to);
}
else if(isObject(to)) {
return transduce(from, xform, objReducer, to);
}
else if(fulfillsProtocol(to, 'transformer')) {
return transduce(from,
xform,
getProtocolProperty(to, 'transformer'),
to);
}
throwProtocolError('into', to);
}
// laziness
var stepper = {
result: function(v) {
return isReduced(v) ? deref(v) : v;
},
step: function(lt, x) {
lt.items.push(x);
return lt.rest;
}
}
function Stepper(xform, iter) {
this.xform = xform(stepper);
this.iter = iter;
}
Stepper.prototype.step = function(lt) {
var len = lt.items.length;
while(lt.items.length === len) {
var n = this.iter.next();
if(n.done || isReduced(n.value)) {
// finalize
this.xform.result(this);
break;
}
// step
this.xform.step(lt, n.value);
}
}
function LazyTransformer(xform, coll) {
this.iter = iterator(coll);
this.items = [];
this.stepper = new Stepper(xform, iterator(coll));
}
LazyTransformer.prototype[protocols.iterator] = function() {
return this;
}
LazyTransformer.prototype.next = function() {
this.step();
if(this.items.length) {
return {
value: this.items.pop(),
done: false
}
}
else {
return { done: true };
}
};
LazyTransformer.prototype.step = function() {
if(!this.items.length) {
this.stepper.step(this);
}
}
// util
function range(n) {
var arr = new Array(n);
for(var i=0; i<arr.length; i++) {
arr[i] = i;
}
return arr;
}
module.exports = {
reduce: reduce,
transformer: transformer,
Reduced: Reduced,
iterator: iterator,
push: push,
merge: merge,
transduce: transduce,
seq: seq,
toArray: toArray,
toObj: toObj,
toIter: toIter,
into: into,
compose: compose,
map: map,
filter: filter,
remove: remove,
cat: cat,
mapcat: mapcat,
keep: keep,
dedupe: dedupe,
take: take,
takeWhile: takeWhile,
drop: drop,
dropWhile: dropWhile,
partition: partition,
partitionBy: partitionBy,
range: range,
protocols: protocols,
LazyTransformer: LazyTransformer
};
/***/ }
/******/ ])
<MSG> push out updated benchmark link from post; update browser build
<DFF> @@ -132,9 +132,6 @@ var transducers =
// helpers
- function isArray(x) {
- return x instanceof Array;
- }
var toString = Object.prototype.toString;
var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) {
return toString.call(obj) == '[object Array]';
@@ -207,7 +204,7 @@ var transducers =
// transformations
- function reducer(f) {
+ function transformer(f) {
return {
init: function() {
throw new Error('init value unavailable');
@@ -656,7 +653,7 @@ var transducers =
else if(isObject(to)) {
return transduce(from, xform, objReducer, to);
}
- else if(fulfillsProtocol(to, 'tranformer')) {
+ else if(fulfillsProtocol(to, 'transformer')) {
return transduce(from,
xform,
getProtocolProperty(to, 'transformer'),
@@ -703,7 +700,7 @@ var transducers =
this.stepper = new Stepper(xform, iterator(coll));
}
- LazyTransformer.prototype['@@iterator'] = function() {
+ LazyTransformer.prototype[protocols.iterator] = function() {
return this;
}
@@ -740,7 +737,7 @@ var transducers =
module.exports = {
reduce: reduce,
- reducer: reducer,
+ transformer: transformer,
Reduced: Reduced,
iterator: iterator,
push: push,
| 4 | push out updated benchmark link from post; update browser build | 7 | .js | js | bsd-2-clause | jlongster/transducers.js |
10071426 | <NME> webpack.config.js
<BEF> var path = require('path');
var webpack = require('webpack');
var VERSION = require('./package.json').version;
var banner =
'/*!\n' +
' * Semantic-UI AngularJS integration\n' +
' * https://github.com/semantic-org/semantic-ui-angular\n' +
' * @license MIT\n' +
' * v' + VERSION + '\n' +
' */\n';
module.exports = {
context: path.resolve('src'),
devtool: "source-map",
entry: {
'semantic-ui-angular': './index',
'semantic-ui-angular.min': './index'
},
output: {
path: path.resolve('dist'),
filename: '[name].js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
}),
new webpack.BannerPlugin(banner, {raw: true})
],
module: {
preLoaders: [
{ test: /\.ts$/, exclude: /node_modules/, loader: 'tslint-loader' },
{ test: /\.ts$/, exclude: /node_modules/, loader: 'jscs-loader' }
],
loaders: [
{ test: /\.ts?$/, exclude: /node_modules/, loader: 'ts-loader' },
{ test: /\.json?$/, exclude: /node_modules/, loader: 'json-loader' }
]
},
tslint: {
configuration: require('./tslint.json')
},
resolve: {
extensions: ['', '.ts', '.js']
}
};
<MSG> refactor(components): Migrate sm-buttom component to TS
<DFF> @@ -31,7 +31,8 @@ module.exports = {
module: {
preLoaders: [
{ test: /\.ts$/, exclude: /node_modules/, loader: 'tslint-loader' },
- { test: /\.ts$/, exclude: /node_modules/, loader: 'jscs-loader' }
+ // TODO: JSCS complains on TS code, decide if we actually can/need make it work
+ //{ test: /\.ts$/, exclude: /node_modules/, loader: 'jscs-loader' }
],
loaders: [
{ test: /\.ts?$/, exclude: /node_modules/, loader: 'ts-loader' },
| 2 | refactor(components): Migrate sm-buttom component to TS | 1 | .js | config | mit | Semantic-Org/Semantic-UI-Angular |
10071427 | <NME> webpack.config.js
<BEF> var path = require('path');
var webpack = require('webpack');
var VERSION = require('./package.json').version;
var banner =
'/*!\n' +
' * Semantic-UI AngularJS integration\n' +
' * https://github.com/semantic-org/semantic-ui-angular\n' +
' * @license MIT\n' +
' * v' + VERSION + '\n' +
' */\n';
module.exports = {
context: path.resolve('src'),
devtool: "source-map",
entry: {
'semantic-ui-angular': './index',
'semantic-ui-angular.min': './index'
},
output: {
path: path.resolve('dist'),
filename: '[name].js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
}),
new webpack.BannerPlugin(banner, {raw: true})
],
module: {
preLoaders: [
{ test: /\.ts$/, exclude: /node_modules/, loader: 'tslint-loader' },
{ test: /\.ts$/, exclude: /node_modules/, loader: 'jscs-loader' }
],
loaders: [
{ test: /\.ts?$/, exclude: /node_modules/, loader: 'ts-loader' },
{ test: /\.json?$/, exclude: /node_modules/, loader: 'json-loader' }
]
},
tslint: {
configuration: require('./tslint.json')
},
resolve: {
extensions: ['', '.ts', '.js']
}
};
<MSG> refactor(components): Migrate sm-buttom component to TS
<DFF> @@ -31,7 +31,8 @@ module.exports = {
module: {
preLoaders: [
{ test: /\.ts$/, exclude: /node_modules/, loader: 'tslint-loader' },
- { test: /\.ts$/, exclude: /node_modules/, loader: 'jscs-loader' }
+ // TODO: JSCS complains on TS code, decide if we actually can/need make it work
+ //{ test: /\.ts$/, exclude: /node_modules/, loader: 'jscs-loader' }
],
loaders: [
{ test: /\.ts?$/, exclude: /node_modules/, loader: 'ts-loader' },
| 2 | refactor(components): Migrate sm-buttom component to TS | 1 | .js | config | mit | Semantic-Org/Semantic-UI-Angular |
10071428 | <NME> webpack.config.js
<BEF> var path = require('path');
var webpack = require('webpack');
var VERSION = require('./package.json').version;
var banner =
'/*!\n' +
' * Semantic-UI AngularJS integration\n' +
' * https://github.com/semantic-org/semantic-ui-angular\n' +
' * @license MIT\n' +
' * v' + VERSION + '\n' +
' */\n';
module.exports = {
context: path.resolve('src'),
devtool: "source-map",
entry: {
'semantic-ui-angular': './index',
'semantic-ui-angular.min': './index'
},
output: {
path: path.resolve('dist'),
filename: '[name].js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
}),
new webpack.BannerPlugin(banner, {raw: true})
],
module: {
preLoaders: [
{ test: /\.ts$/, exclude: /node_modules/, loader: 'tslint-loader' },
{ test: /\.ts$/, exclude: /node_modules/, loader: 'jscs-loader' }
],
loaders: [
{ test: /\.ts?$/, exclude: /node_modules/, loader: 'ts-loader' },
{ test: /\.json?$/, exclude: /node_modules/, loader: 'json-loader' }
]
},
tslint: {
configuration: require('./tslint.json')
},
resolve: {
extensions: ['', '.ts', '.js']
}
};
<MSG> refactor(components): Migrate sm-buttom component to TS
<DFF> @@ -31,7 +31,8 @@ module.exports = {
module: {
preLoaders: [
{ test: /\.ts$/, exclude: /node_modules/, loader: 'tslint-loader' },
- { test: /\.ts$/, exclude: /node_modules/, loader: 'jscs-loader' }
+ // TODO: JSCS complains on TS code, decide if we actually can/need make it work
+ //{ test: /\.ts$/, exclude: /node_modules/, loader: 'jscs-loader' }
],
loaders: [
{ test: /\.ts?$/, exclude: /node_modules/, loader: 'ts-loader' },
| 2 | refactor(components): Migrate sm-buttom component to TS | 1 | .js | config | mit | Semantic-Org/Semantic-UI-Angular |
10071429 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new('red', 'link_color').participant_count
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #544 from splitrb/exclude-visitor-before-loading-experiment
Avoid hitting up on redis for robots/excluded users.
<DFF> @@ -564,6 +564,11 @@ describe Split::Helper do
expect(alternative).to eq experiment.control.name
end
+ it 'should not create a experiment' do
+ ab_test('link_color', 'blue', 'red')
+ expect(Split::Experiment.new('link_color')).to be_a_new_record
+ end
+
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new('red', 'link_color').participant_count
| 5 | Merge pull request #544 from splitrb/exclude-visitor-before-loading-experiment | 0 | .rb | rb | mit | splitrb/split |
10071430 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new('red', 'link_color').participant_count
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #544 from splitrb/exclude-visitor-before-loading-experiment
Avoid hitting up on redis for robots/excluded users.
<DFF> @@ -564,6 +564,11 @@ describe Split::Helper do
expect(alternative).to eq experiment.control.name
end
+ it 'should not create a experiment' do
+ ab_test('link_color', 'blue', 'red')
+ expect(Split::Experiment.new('link_color')).to be_a_new_record
+ end
+
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new('red', 'link_color').participant_count
| 5 | Merge pull request #544 from splitrb/exclude-visitor-before-loading-experiment | 0 | .rb | rb | mit | splitrb/split |
10071431 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
@params = { "ab_test" => { "test_1" => "test-alt" } }
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control"
expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
end
end
end
it "should not over-write a finished key when an experiment is on a later version" do
experiment.increment_version
ab_user = { experiment.key => "blue", experiment.finished_key => true }
finished_session = ab_user.dup
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new('red', 'link_color').participant_count
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Merge pull request #544 from splitrb/exclude-visitor-before-loading-experiment
Avoid hitting up on redis for robots/excluded users.
<DFF> @@ -564,6 +564,11 @@ describe Split::Helper do
expect(alternative).to eq experiment.control.name
end
+ it 'should not create a experiment' do
+ ab_test('link_color', 'blue', 'red')
+ expect(Split::Experiment.new('link_color')).to be_a_new_record
+ end
+
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new('red', 'link_color').participant_count
| 5 | Merge pull request #544 from splitrb/exclude-visitor-before-loading-experiment | 0 | .rb | rb | mit | splitrb/split |
10071432 | <NME> index.erb
<BEF> <% if @experiments.any? %>
<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p>
<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p>
<% @experiments.each do |experiment| %>
<h2><%= experiment.name %></h2>
<form action="<%= url "/reset/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmReset()">
<input type="submit" value="Reset Data">
</form>
<form action="<%= url "/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmDelete()">
<input type="hidden" name="_method" value="delete"/>
<input type="submit" value="Delete">
</form>
<table class="queues">
<tr>
<th>Alternative Name</th>
<th>Participants</th>
<th>Non-finished</th>
<th>Completed</th>
<th>Conversion Rate</th>
<th>Z-Score</th>
<th>Winner</th>
</tr>
<% total_participants = total_completed = 0 %>
<% experiment.alternatives.each do |alternative| %>
<tr>
<td><%= alternative.name %></td>
<td><%= alternative.participant_count %></td>
<td><%= alternative.participant_count - alternative.completed_count %></td>
<td><%= alternative.completed_count %></td>
<td>
<%= number_to_percentage(alternative.conversion_rate) %>%
<% if experiment.control.conversion_rate > 0 && !alternative.control? %>
<% if alternative.conversion_rate > experiment.control.conversion_rate %>
<span class='better'>
+<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
</span>
<% elsif alternative.conversion_rate < experiment.control.conversion_rate %>
<span class='worse'>
<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
</span>
<% end %>
<% end %>
</td>
<td><%= round(alternative.z_score, 3) %></td>
<td>
<% if experiment.winner %>
<% if experiment.winner.name == alternative.name %>
Winner
<% else %>
Loser
<% end %>
<% else %>
<form action="<%= url experiment.name %>" method='post' onclick="return confirmWinner()">
<input type='hidden' name='alternative' value='<%= alternative.name %>'>
<input type="submit" value="Use this">
</form>
<% end %>
</td>
</tr>
<% total_participants += alternative.participant_count %>
<% total_completed += alternative.completed_count %>
<% end %>
<tr class="totals">
<td>Totals</td>
<td><%= total_participants %></td>
<td><%= total_participants - total_completed %></td>
<td><%= total_completed %></td>
<td>N/A</td>
<td>N/A</td>
<td>N/A</td>
</tr>
</table>
<% end %>
<% else %>
<p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p>
<% paginated(@experiments).each do |experiment| %>
<% if experiment.goals.empty? %>
<%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %>
<% else %>
<%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %>
<% experiment.goals.each do |g| %>
<%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %>
<% end %>
<% end %>
<% end %>
<div class="pagination">
<%= pagination(@experiments) %>
</div>
<% else %>
<p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p>
<p class="intro">Check out the <a href='https://github.com/splitrb/split#readme'>Readme</a> for more help getting started.</p>
<% end %>
<div class="dashboard-controls dashboard-controls-bottom">
<form action="<%= url "/initialize_experiment" %>" method='post'>
<label>Add unregistered experiment: </label>
<select name="experiment" id="experiment-select">
<option selected disabled>experiment</option>
<% @unintialized_experiments.sort.each do |experiment_name| %>
<option value="<%= experiment_name %>"><%= experiment_name %></option>
<% end %>
</select>
<input type="submit" id="register-experiment-btn" value="register experiment"/>
</form>
<div>
<MSG> Extracted dashboard experiment html into a partial
<DFF> @@ -3,77 +3,7 @@
<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p>
<% @experiments.each do |experiment| %>
- <h2><%= experiment.name %></h2>
- <form action="<%= url "/reset/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmReset()">
- <input type="submit" value="Reset Data">
- </form>
- <form action="<%= url "/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmDelete()">
- <input type="hidden" name="_method" value="delete"/>
- <input type="submit" value="Delete">
- </form>
- <table class="queues">
- <tr>
- <th>Alternative Name</th>
- <th>Participants</th>
- <th>Non-finished</th>
- <th>Completed</th>
- <th>Conversion Rate</th>
- <th>Z-Score</th>
- <th>Winner</th>
- </tr>
-
- <% total_participants = total_completed = 0 %>
- <% experiment.alternatives.each do |alternative| %>
- <tr>
- <td><%= alternative.name %></td>
- <td><%= alternative.participant_count %></td>
- <td><%= alternative.participant_count - alternative.completed_count %></td>
- <td><%= alternative.completed_count %></td>
- <td>
- <%= number_to_percentage(alternative.conversion_rate) %>%
- <% if experiment.control.conversion_rate > 0 && !alternative.control? %>
- <% if alternative.conversion_rate > experiment.control.conversion_rate %>
- <span class='better'>
- +<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
- </span>
- <% elsif alternative.conversion_rate < experiment.control.conversion_rate %>
- <span class='worse'>
- <%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
- </span>
- <% end %>
- <% end %>
- </td>
- <td><%= round(alternative.z_score, 3) %></td>
- <td>
- <% if experiment.winner %>
- <% if experiment.winner.name == alternative.name %>
- Winner
- <% else %>
- Loser
- <% end %>
- <% else %>
- <form action="<%= url experiment.name %>" method='post' onclick="return confirmWinner()">
- <input type='hidden' name='alternative' value='<%= alternative.name %>'>
- <input type="submit" value="Use this">
- </form>
- <% end %>
- </td>
- </tr>
-
- <% total_participants += alternative.participant_count %>
- <% total_completed += alternative.completed_count %>
- <% end %>
-
- <tr class="totals">
- <td>Totals</td>
- <td><%= total_participants %></td>
- <td><%= total_participants - total_completed %></td>
- <td><%= total_completed %></td>
- <td>N/A</td>
- <td>N/A</td>
- <td>N/A</td>
- </tr>
- </table>
+ <%= erb :_experiment, :locals => {:experiment => experiment} %>
<% end %>
<% else %>
<p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p>
| 1 | Extracted dashboard experiment html into a partial | 71 | .erb | erb | mit | splitrb/split |
10071433 | <NME> index.erb
<BEF> <% if @experiments.any? %>
<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p>
<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p>
<% @experiments.each do |experiment| %>
<h2><%= experiment.name %></h2>
<form action="<%= url "/reset/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmReset()">
<input type="submit" value="Reset Data">
</form>
<form action="<%= url "/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmDelete()">
<input type="hidden" name="_method" value="delete"/>
<input type="submit" value="Delete">
</form>
<table class="queues">
<tr>
<th>Alternative Name</th>
<th>Participants</th>
<th>Non-finished</th>
<th>Completed</th>
<th>Conversion Rate</th>
<th>Z-Score</th>
<th>Winner</th>
</tr>
<% total_participants = total_completed = 0 %>
<% experiment.alternatives.each do |alternative| %>
<tr>
<td><%= alternative.name %></td>
<td><%= alternative.participant_count %></td>
<td><%= alternative.participant_count - alternative.completed_count %></td>
<td><%= alternative.completed_count %></td>
<td>
<%= number_to_percentage(alternative.conversion_rate) %>%
<% if experiment.control.conversion_rate > 0 && !alternative.control? %>
<% if alternative.conversion_rate > experiment.control.conversion_rate %>
<span class='better'>
+<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
</span>
<% elsif alternative.conversion_rate < experiment.control.conversion_rate %>
<span class='worse'>
<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
</span>
<% end %>
<% end %>
</td>
<td><%= round(alternative.z_score, 3) %></td>
<td>
<% if experiment.winner %>
<% if experiment.winner.name == alternative.name %>
Winner
<% else %>
Loser
<% end %>
<% else %>
<form action="<%= url experiment.name %>" method='post' onclick="return confirmWinner()">
<input type='hidden' name='alternative' value='<%= alternative.name %>'>
<input type="submit" value="Use this">
</form>
<% end %>
</td>
</tr>
<% total_participants += alternative.participant_count %>
<% total_completed += alternative.completed_count %>
<% end %>
<tr class="totals">
<td>Totals</td>
<td><%= total_participants %></td>
<td><%= total_participants - total_completed %></td>
<td><%= total_completed %></td>
<td>N/A</td>
<td>N/A</td>
<td>N/A</td>
</tr>
</table>
<% end %>
<% else %>
<p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p>
<% paginated(@experiments).each do |experiment| %>
<% if experiment.goals.empty? %>
<%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %>
<% else %>
<%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %>
<% experiment.goals.each do |g| %>
<%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %>
<% end %>
<% end %>
<% end %>
<div class="pagination">
<%= pagination(@experiments) %>
</div>
<% else %>
<p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p>
<p class="intro">Check out the <a href='https://github.com/splitrb/split#readme'>Readme</a> for more help getting started.</p>
<% end %>
<div class="dashboard-controls dashboard-controls-bottom">
<form action="<%= url "/initialize_experiment" %>" method='post'>
<label>Add unregistered experiment: </label>
<select name="experiment" id="experiment-select">
<option selected disabled>experiment</option>
<% @unintialized_experiments.sort.each do |experiment_name| %>
<option value="<%= experiment_name %>"><%= experiment_name %></option>
<% end %>
</select>
<input type="submit" id="register-experiment-btn" value="register experiment"/>
</form>
<div>
<MSG> Extracted dashboard experiment html into a partial
<DFF> @@ -3,77 +3,7 @@
<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p>
<% @experiments.each do |experiment| %>
- <h2><%= experiment.name %></h2>
- <form action="<%= url "/reset/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmReset()">
- <input type="submit" value="Reset Data">
- </form>
- <form action="<%= url "/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmDelete()">
- <input type="hidden" name="_method" value="delete"/>
- <input type="submit" value="Delete">
- </form>
- <table class="queues">
- <tr>
- <th>Alternative Name</th>
- <th>Participants</th>
- <th>Non-finished</th>
- <th>Completed</th>
- <th>Conversion Rate</th>
- <th>Z-Score</th>
- <th>Winner</th>
- </tr>
-
- <% total_participants = total_completed = 0 %>
- <% experiment.alternatives.each do |alternative| %>
- <tr>
- <td><%= alternative.name %></td>
- <td><%= alternative.participant_count %></td>
- <td><%= alternative.participant_count - alternative.completed_count %></td>
- <td><%= alternative.completed_count %></td>
- <td>
- <%= number_to_percentage(alternative.conversion_rate) %>%
- <% if experiment.control.conversion_rate > 0 && !alternative.control? %>
- <% if alternative.conversion_rate > experiment.control.conversion_rate %>
- <span class='better'>
- +<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
- </span>
- <% elsif alternative.conversion_rate < experiment.control.conversion_rate %>
- <span class='worse'>
- <%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
- </span>
- <% end %>
- <% end %>
- </td>
- <td><%= round(alternative.z_score, 3) %></td>
- <td>
- <% if experiment.winner %>
- <% if experiment.winner.name == alternative.name %>
- Winner
- <% else %>
- Loser
- <% end %>
- <% else %>
- <form action="<%= url experiment.name %>" method='post' onclick="return confirmWinner()">
- <input type='hidden' name='alternative' value='<%= alternative.name %>'>
- <input type="submit" value="Use this">
- </form>
- <% end %>
- </td>
- </tr>
-
- <% total_participants += alternative.participant_count %>
- <% total_completed += alternative.completed_count %>
- <% end %>
-
- <tr class="totals">
- <td>Totals</td>
- <td><%= total_participants %></td>
- <td><%= total_participants - total_completed %></td>
- <td><%= total_completed %></td>
- <td>N/A</td>
- <td>N/A</td>
- <td>N/A</td>
- </tr>
- </table>
+ <%= erb :_experiment, :locals => {:experiment => experiment} %>
<% end %>
<% else %>
<p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p>
| 1 | Extracted dashboard experiment html into a partial | 71 | .erb | erb | mit | splitrb/split |
10071434 | <NME> index.erb
<BEF> <% if @experiments.any? %>
<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p>
<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p>
<% @experiments.each do |experiment| %>
<h2><%= experiment.name %></h2>
<form action="<%= url "/reset/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmReset()">
<input type="submit" value="Reset Data">
</form>
<form action="<%= url "/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmDelete()">
<input type="hidden" name="_method" value="delete"/>
<input type="submit" value="Delete">
</form>
<table class="queues">
<tr>
<th>Alternative Name</th>
<th>Participants</th>
<th>Non-finished</th>
<th>Completed</th>
<th>Conversion Rate</th>
<th>Z-Score</th>
<th>Winner</th>
</tr>
<% total_participants = total_completed = 0 %>
<% experiment.alternatives.each do |alternative| %>
<tr>
<td><%= alternative.name %></td>
<td><%= alternative.participant_count %></td>
<td><%= alternative.participant_count - alternative.completed_count %></td>
<td><%= alternative.completed_count %></td>
<td>
<%= number_to_percentage(alternative.conversion_rate) %>%
<% if experiment.control.conversion_rate > 0 && !alternative.control? %>
<% if alternative.conversion_rate > experiment.control.conversion_rate %>
<span class='better'>
+<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
</span>
<% elsif alternative.conversion_rate < experiment.control.conversion_rate %>
<span class='worse'>
<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
</span>
<% end %>
<% end %>
</td>
<td><%= round(alternative.z_score, 3) %></td>
<td>
<% if experiment.winner %>
<% if experiment.winner.name == alternative.name %>
Winner
<% else %>
Loser
<% end %>
<% else %>
<form action="<%= url experiment.name %>" method='post' onclick="return confirmWinner()">
<input type='hidden' name='alternative' value='<%= alternative.name %>'>
<input type="submit" value="Use this">
</form>
<% end %>
</td>
</tr>
<% total_participants += alternative.participant_count %>
<% total_completed += alternative.completed_count %>
<% end %>
<tr class="totals">
<td>Totals</td>
<td><%= total_participants %></td>
<td><%= total_participants - total_completed %></td>
<td><%= total_completed %></td>
<td>N/A</td>
<td>N/A</td>
<td>N/A</td>
</tr>
</table>
<% end %>
<% else %>
<p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p>
<% paginated(@experiments).each do |experiment| %>
<% if experiment.goals.empty? %>
<%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %>
<% else %>
<%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %>
<% experiment.goals.each do |g| %>
<%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %>
<% end %>
<% end %>
<% end %>
<div class="pagination">
<%= pagination(@experiments) %>
</div>
<% else %>
<p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p>
<p class="intro">Check out the <a href='https://github.com/splitrb/split#readme'>Readme</a> for more help getting started.</p>
<% end %>
<div class="dashboard-controls dashboard-controls-bottom">
<form action="<%= url "/initialize_experiment" %>" method='post'>
<label>Add unregistered experiment: </label>
<select name="experiment" id="experiment-select">
<option selected disabled>experiment</option>
<% @unintialized_experiments.sort.each do |experiment_name| %>
<option value="<%= experiment_name %>"><%= experiment_name %></option>
<% end %>
</select>
<input type="submit" id="register-experiment-btn" value="register experiment"/>
</form>
<div>
<MSG> Extracted dashboard experiment html into a partial
<DFF> @@ -3,77 +3,7 @@
<p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p>
<% @experiments.each do |experiment| %>
- <h2><%= experiment.name %></h2>
- <form action="<%= url "/reset/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmReset()">
- <input type="submit" value="Reset Data">
- </form>
- <form action="<%= url "/#{experiment.name}" %>" method='post' class='inline-controls' onclick="return confirmDelete()">
- <input type="hidden" name="_method" value="delete"/>
- <input type="submit" value="Delete">
- </form>
- <table class="queues">
- <tr>
- <th>Alternative Name</th>
- <th>Participants</th>
- <th>Non-finished</th>
- <th>Completed</th>
- <th>Conversion Rate</th>
- <th>Z-Score</th>
- <th>Winner</th>
- </tr>
-
- <% total_participants = total_completed = 0 %>
- <% experiment.alternatives.each do |alternative| %>
- <tr>
- <td><%= alternative.name %></td>
- <td><%= alternative.participant_count %></td>
- <td><%= alternative.participant_count - alternative.completed_count %></td>
- <td><%= alternative.completed_count %></td>
- <td>
- <%= number_to_percentage(alternative.conversion_rate) %>%
- <% if experiment.control.conversion_rate > 0 && !alternative.control? %>
- <% if alternative.conversion_rate > experiment.control.conversion_rate %>
- <span class='better'>
- +<%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
- </span>
- <% elsif alternative.conversion_rate < experiment.control.conversion_rate %>
- <span class='worse'>
- <%= number_to_percentage((alternative.conversion_rate/experiment.control.conversion_rate)-1) %>%
- </span>
- <% end %>
- <% end %>
- </td>
- <td><%= round(alternative.z_score, 3) %></td>
- <td>
- <% if experiment.winner %>
- <% if experiment.winner.name == alternative.name %>
- Winner
- <% else %>
- Loser
- <% end %>
- <% else %>
- <form action="<%= url experiment.name %>" method='post' onclick="return confirmWinner()">
- <input type='hidden' name='alternative' value='<%= alternative.name %>'>
- <input type="submit" value="Use this">
- </form>
- <% end %>
- </td>
- </tr>
-
- <% total_participants += alternative.participant_count %>
- <% total_completed += alternative.completed_count %>
- <% end %>
-
- <tr class="totals">
- <td>Totals</td>
- <td><%= total_participants %></td>
- <td><%= total_participants - total_completed %></td>
- <td><%= total_completed %></td>
- <td>N/A</td>
- <td>N/A</td>
- <td>N/A</td>
- </tr>
- </table>
+ <%= erb :_experiment, :locals => {:experiment => experiment} %>
<% end %>
<% else %>
<p class="intro">No experiments have started yet, you need to define them in your code and introduce them to your users.</p>
| 1 | Extracted dashboard experiment html into a partial | 71 | .erb | erb | mit | splitrb/split |
10071435 | <NME> whiplash.rb
<BEF> # frozen_string_literal: true
# A multi-armed bandit implementation inspired by
# @aaronsw and victorykit/whiplash
module Split
module Algorithms
module Whiplash
class << self
end
private
def self.arm_guess(participants, completions)
a = [participants, 0].max
b = [participants-completions, 0].max
s = SimpleRandom.new; s.set_seed; s.beta(a+fairness_constant, b+fairness_constant)
end
def self.best_guess(alternatives)
guesses = {}
alternatives.each do |alternative|
guesses[alternative.name] = arm_guess(alternative.participant_count, alternative.completed_count)
end
gmax = guesses.values.max
best = guesses.keys.select {|name| guesses[name] == gmax }
return best.sample
end
def self.fairness_constant
7
end
end
end
end
end
end
<MSG> Whiplash: use all_completed_count instead of completed_count to take goal completions into account
<DFF> @@ -10,26 +10,26 @@ module Split
end
private
-
+
def self.arm_guess(participants, completions)
a = [participants, 0].max
b = [participants-completions, 0].max
s = SimpleRandom.new; s.set_seed; s.beta(a+fairness_constant, b+fairness_constant)
end
-
+
def self.best_guess(alternatives)
guesses = {}
- alternatives.each do |alternative|
- guesses[alternative.name] = arm_guess(alternative.participant_count, alternative.completed_count)
+ alternatives.each do |alternative|
+ guesses[alternative.name] = arm_guess(alternative.participant_count, alternative.all_completed_count)
end
gmax = guesses.values.max
best = guesses.keys.select {|name| guesses[name] == gmax }
return best.sample
end
-
+
def self.fairness_constant
7
end
end
end
-end
\ No newline at end of file
+end
| 6 | Whiplash: use all_completed_count instead of completed_count to take goal completions into account | 6 | .rb | rb | mit | splitrb/split |
10071436 | <NME> whiplash.rb
<BEF> # frozen_string_literal: true
# A multi-armed bandit implementation inspired by
# @aaronsw and victorykit/whiplash
module Split
module Algorithms
module Whiplash
class << self
end
private
def self.arm_guess(participants, completions)
a = [participants, 0].max
b = [participants-completions, 0].max
s = SimpleRandom.new; s.set_seed; s.beta(a+fairness_constant, b+fairness_constant)
end
def self.best_guess(alternatives)
guesses = {}
alternatives.each do |alternative|
guesses[alternative.name] = arm_guess(alternative.participant_count, alternative.completed_count)
end
gmax = guesses.values.max
best = guesses.keys.select {|name| guesses[name] == gmax }
return best.sample
end
def self.fairness_constant
7
end
end
end
end
end
end
<MSG> Whiplash: use all_completed_count instead of completed_count to take goal completions into account
<DFF> @@ -10,26 +10,26 @@ module Split
end
private
-
+
def self.arm_guess(participants, completions)
a = [participants, 0].max
b = [participants-completions, 0].max
s = SimpleRandom.new; s.set_seed; s.beta(a+fairness_constant, b+fairness_constant)
end
-
+
def self.best_guess(alternatives)
guesses = {}
- alternatives.each do |alternative|
- guesses[alternative.name] = arm_guess(alternative.participant_count, alternative.completed_count)
+ alternatives.each do |alternative|
+ guesses[alternative.name] = arm_guess(alternative.participant_count, alternative.all_completed_count)
end
gmax = guesses.values.max
best = guesses.keys.select {|name| guesses[name] == gmax }
return best.sample
end
-
+
def self.fairness_constant
7
end
end
end
-end
\ No newline at end of file
+end
| 6 | Whiplash: use all_completed_count instead of completed_count to take goal completions into account | 6 | .rb | rb | mit | splitrb/split |
10071437 | <NME> whiplash.rb
<BEF> # frozen_string_literal: true
# A multi-armed bandit implementation inspired by
# @aaronsw and victorykit/whiplash
module Split
module Algorithms
module Whiplash
class << self
end
private
def self.arm_guess(participants, completions)
a = [participants, 0].max
b = [participants-completions, 0].max
s = SimpleRandom.new; s.set_seed; s.beta(a+fairness_constant, b+fairness_constant)
end
def self.best_guess(alternatives)
guesses = {}
alternatives.each do |alternative|
guesses[alternative.name] = arm_guess(alternative.participant_count, alternative.completed_count)
end
gmax = guesses.values.max
best = guesses.keys.select {|name| guesses[name] == gmax }
return best.sample
end
def self.fairness_constant
7
end
end
end
end
end
end
<MSG> Whiplash: use all_completed_count instead of completed_count to take goal completions into account
<DFF> @@ -10,26 +10,26 @@ module Split
end
private
-
+
def self.arm_guess(participants, completions)
a = [participants, 0].max
b = [participants-completions, 0].max
s = SimpleRandom.new; s.set_seed; s.beta(a+fairness_constant, b+fairness_constant)
end
-
+
def self.best_guess(alternatives)
guesses = {}
- alternatives.each do |alternative|
- guesses[alternative.name] = arm_guess(alternative.participant_count, alternative.completed_count)
+ alternatives.each do |alternative|
+ guesses[alternative.name] = arm_guess(alternative.participant_count, alternative.all_completed_count)
end
gmax = guesses.values.max
best = guesses.keys.select {|name| guesses[name] == gmax }
return best.sample
end
-
+
def self.fairness_constant
7
end
end
end
-end
\ No newline at end of file
+end
| 6 | Whiplash: use all_completed_count instead of completed_count to take goal completions into account | 6 | .rb | rb | mit | splitrb/split |
10071438 | <NME> parser.ts
<BEF> import { strictEqual as equal, throws } from 'assert';
import parser, { ParseOptions, FunctionCall } from '../src/parser';
import tokenizer from '../src/tokenizer';
import stringify from './assets/stringify';
const parse = (abbr: string, opt?: ParseOptions) => parser(tokenizer(abbr), opt);
const expand = (abbr: string) => parse(abbr).map(stringify).join('');
describe('CSS Abbreviation parser', () => {
it('basic', () => {
equal(expand('p10!'), 'p: 10 !important;');
equal(expand('p-10-20'), 'p: -10 20;');
equal(expand('p-10%-20--30'), 'p: -10% -20 -30;');
equal(expand('p.5'), 'p: 0.5;');
equal(expand('p-.5'), 'p: -0.5;');
equal(expand('p.1.2.3'), 'p: 0.1 0.2 0.3;');
equal(expand('p.1-.2.3'), 'p: 0.1 0.2 0.3;');
equal(expand('10'), '?: 10;');
equal(expand('.1'), '?: 0.1;');
equal(expand('lh1.'), 'lh: 1;');
});
it('color', () => {
equal(expand('c#'), 'c: #000000;');
equal(expand('c#1'), 'c: #111111;');
equal(expand('c#f'), 'c: #ffffff;');
equal(expand('c#a#b#c'), 'c: #aaaaaa #bbbbbb #cccccc;');
equal(expand('c#af'), 'c: #afafaf;');
equal(expand('c#fc0'), 'c: #ffcc00;');
equal(expand('c#11.5'), 'c: rgba(17, 17, 17, 0.5);');
equal(expand('c#.99'), 'c: rgba(0, 0, 0, 0.99);');
equal(expand('c#t'), 'c: transparent;');
});
it('keywords', () => {
equal(expand('m:a'), 'm: a;');
equal(expand('m-a'), 'm: a;');
equal(expand('m-abc'), 'm: abc;');
equal(expand('m-a0'), 'm: a 0;');
equal(expand('m-a0-a'), 'm: a 0 a;');
});
it('functions', () => {
equal(expand('bg-lg(top, "red, black",rgb(0, 0, 0) 10%)'), 'bg: lg(top, "red, black", rgb(0, 0, 0) 10%);');
equal(expand('lg(top, "red, black",rgb(0, 0, 0) 10%)'), '?: lg(top, "red, black", rgb(0, 0, 0) 10%);');
});
it('mixed', () => {
equal(expand('bd1-s#fc0'), 'bd: 1 s #ffcc00;');
equal(expand('bd#fc0-1'), 'bd: #ffcc00 1;');
equal(expand('p0+m0'), 'p: 0;m: 0;');
equal(expand('p0!+m0!'), 'p: 0 !important;m: 0 !important;');
});
it('embedded variables', () => {
equal(expand('foo$bar'), 'foo: $bar;');
equal(expand('foo$bar-2'), 'foo: $bar-2;');
equal(expand('foo$bar@bam'), 'foo: $bar @bam;');
});
it('parse value', () => {
const opt: ParseOptions = { value: true };
let prop = parse('${1:foo} ${2:bar}, baz', opt)[0];
equal(prop.name, undefined);
equal(prop.value.length, 2);
equal(prop.value[0].value.length, 2);
equal(prop.value[0].value[0].type, 'Field');
prop = parse('scale3d(${1:x}, ${2:y}, ${3:z})', opt)[0];
const fn = prop.value[0].value[0] as FunctionCall;
equal(prop.value.length, 1);
equal(prop.value[0].value.length, 1);
equal(fn.type, 'FunctionCall');
equal(fn.name, 'scale3d');
});
it('errors', () => {
throws(() => expand('p10 '), /Unexpected token/);
});
});
<MSG> Support slash in CSS attribute values
<DFF> @@ -72,6 +72,9 @@ describe('CSS Abbreviation parser', () => {
equal(prop.value[0].value.length, 1);
equal(fn.type, 'FunctionCall');
equal(fn.name, 'scale3d');
+
+ prop = parse('repeat(2,auto) / repeat(auto-fit, minmax(250px, 1fr))', opt)[0];
+ equal(prop.value.length, 2);
});
it('errors', () => {
| 3 | Support slash in CSS attribute values | 0 | .ts | ts | mit | emmetio/emmet |
10071439 | <NME> parser.ts
<BEF> import { strictEqual as equal, throws } from 'assert';
import parser, { ParseOptions, FunctionCall } from '../src/parser';
import tokenizer from '../src/tokenizer';
import stringify from './assets/stringify';
const parse = (abbr: string, opt?: ParseOptions) => parser(tokenizer(abbr), opt);
const expand = (abbr: string) => parse(abbr).map(stringify).join('');
describe('CSS Abbreviation parser', () => {
it('basic', () => {
equal(expand('p10!'), 'p: 10 !important;');
equal(expand('p-10-20'), 'p: -10 20;');
equal(expand('p-10%-20--30'), 'p: -10% -20 -30;');
equal(expand('p.5'), 'p: 0.5;');
equal(expand('p-.5'), 'p: -0.5;');
equal(expand('p.1.2.3'), 'p: 0.1 0.2 0.3;');
equal(expand('p.1-.2.3'), 'p: 0.1 0.2 0.3;');
equal(expand('10'), '?: 10;');
equal(expand('.1'), '?: 0.1;');
equal(expand('lh1.'), 'lh: 1;');
});
it('color', () => {
equal(expand('c#'), 'c: #000000;');
equal(expand('c#1'), 'c: #111111;');
equal(expand('c#f'), 'c: #ffffff;');
equal(expand('c#a#b#c'), 'c: #aaaaaa #bbbbbb #cccccc;');
equal(expand('c#af'), 'c: #afafaf;');
equal(expand('c#fc0'), 'c: #ffcc00;');
equal(expand('c#11.5'), 'c: rgba(17, 17, 17, 0.5);');
equal(expand('c#.99'), 'c: rgba(0, 0, 0, 0.99);');
equal(expand('c#t'), 'c: transparent;');
});
it('keywords', () => {
equal(expand('m:a'), 'm: a;');
equal(expand('m-a'), 'm: a;');
equal(expand('m-abc'), 'm: abc;');
equal(expand('m-a0'), 'm: a 0;');
equal(expand('m-a0-a'), 'm: a 0 a;');
});
it('functions', () => {
equal(expand('bg-lg(top, "red, black",rgb(0, 0, 0) 10%)'), 'bg: lg(top, "red, black", rgb(0, 0, 0) 10%);');
equal(expand('lg(top, "red, black",rgb(0, 0, 0) 10%)'), '?: lg(top, "red, black", rgb(0, 0, 0) 10%);');
});
it('mixed', () => {
equal(expand('bd1-s#fc0'), 'bd: 1 s #ffcc00;');
equal(expand('bd#fc0-1'), 'bd: #ffcc00 1;');
equal(expand('p0+m0'), 'p: 0;m: 0;');
equal(expand('p0!+m0!'), 'p: 0 !important;m: 0 !important;');
});
it('embedded variables', () => {
equal(expand('foo$bar'), 'foo: $bar;');
equal(expand('foo$bar-2'), 'foo: $bar-2;');
equal(expand('foo$bar@bam'), 'foo: $bar @bam;');
});
it('parse value', () => {
const opt: ParseOptions = { value: true };
let prop = parse('${1:foo} ${2:bar}, baz', opt)[0];
equal(prop.name, undefined);
equal(prop.value.length, 2);
equal(prop.value[0].value.length, 2);
equal(prop.value[0].value[0].type, 'Field');
prop = parse('scale3d(${1:x}, ${2:y}, ${3:z})', opt)[0];
const fn = prop.value[0].value[0] as FunctionCall;
equal(prop.value.length, 1);
equal(prop.value[0].value.length, 1);
equal(fn.type, 'FunctionCall');
equal(fn.name, 'scale3d');
});
it('errors', () => {
throws(() => expand('p10 '), /Unexpected token/);
});
});
<MSG> Support slash in CSS attribute values
<DFF> @@ -72,6 +72,9 @@ describe('CSS Abbreviation parser', () => {
equal(prop.value[0].value.length, 1);
equal(fn.type, 'FunctionCall');
equal(fn.name, 'scale3d');
+
+ prop = parse('repeat(2,auto) / repeat(auto-fit, minmax(250px, 1fr))', opt)[0];
+ equal(prop.value.length, 2);
});
it('errors', () => {
| 3 | Support slash in CSS attribute values | 0 | .ts | ts | mit | emmetio/emmet |
10071440 | <NME> LICENSE
<BEF> ADDFILE
<MSG> Added license
<DFF> @@ -0,0 +1,20 @@
+Copyright (c) 2011 Andrew Nesbitt
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
| 20 | Added license | 0 | LICENSE | mit | splitrb/split |
|
10071441 | <NME> LICENSE
<BEF> ADDFILE
<MSG> Added license
<DFF> @@ -0,0 +1,20 @@
+Copyright (c) 2011 Andrew Nesbitt
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
| 20 | Added license | 0 | LICENSE | mit | splitrb/split |
|
10071442 | <NME> LICENSE
<BEF> ADDFILE
<MSG> Added license
<DFF> @@ -0,0 +1,20 @@
+Copyright (c) 2011 Andrew Nesbitt
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
| 20 | Added license | 0 | LICENSE | mit | splitrb/split |
|
10071443 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
module Split
class Experiment
attr_accessor :name
attr_accessor :goals
attr_accessor :alternative_probabilities
attr_accessor :metadata
attr_reader :alternatives
attr_reader :resettable
DEFAULT_OPTIONS = {
resettable: true
}
def self.find(name)
Split.cache(:experiments, name) do
return unless Split.redis.exists?(name)
Experiment.new(name).tap { |exp| exp.load_from_redis }
end
end
def initialize(name, options = {})
options = DEFAULT_OPTIONS.merge(options)
@name = name.to_s
extract_alternatives_from_options(options)
end
def self.finished_key(key)
"#{key}:finished"
end
def set_alternatives_and_options(options)
options_with_defaults = DEFAULT_OPTIONS.merge(
options.reject { |k, v| v.nil? }
)
self.alternatives = options_with_defaults[:alternatives]
self.goals = options_with_defaults[:goals]
self.resettable = options_with_defaults[:resettable]
self.algorithm = options_with_defaults[:algorithm]
self.metadata = options_with_defaults[:metadata]
end
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
if alts[0].is_a? Hash
alts = alts[0].map { |k, v| { k => v } }
end
end
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration
options[:metadata] = load_metadata_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
@alternatives.reverse.each {|a| Split.redis.lpush(name, a.name)}
goals_collection.save
save_metadata
Split.redis.set(metadata_key, @metadata.to_json) unless @metadata.nil?
else
existing_alternatives = load_alternatives_from_redis
existing_goals = Split::GoalsCollection.new(@name).load_from_redis
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub("/", "--")
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Merge pull request #391 from pakallis/remove-obsolete-code-save-metadata
Remove unecessary code from Experiment#save
<DFF> @@ -86,7 +86,6 @@ module Split
@alternatives.reverse.each {|a| Split.redis.lpush(name, a.name)}
goals_collection.save
save_metadata
- Split.redis.set(metadata_key, @metadata.to_json) unless @metadata.nil?
else
existing_alternatives = load_alternatives_from_redis
existing_goals = Split::GoalsCollection.new(@name).load_from_redis
| 0 | Merge pull request #391 from pakallis/remove-obsolete-code-save-metadata | 1 | .rb | rb | mit | splitrb/split |
10071444 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
module Split
class Experiment
attr_accessor :name
attr_accessor :goals
attr_accessor :alternative_probabilities
attr_accessor :metadata
attr_reader :alternatives
attr_reader :resettable
DEFAULT_OPTIONS = {
resettable: true
}
def self.find(name)
Split.cache(:experiments, name) do
return unless Split.redis.exists?(name)
Experiment.new(name).tap { |exp| exp.load_from_redis }
end
end
def initialize(name, options = {})
options = DEFAULT_OPTIONS.merge(options)
@name = name.to_s
extract_alternatives_from_options(options)
end
def self.finished_key(key)
"#{key}:finished"
end
def set_alternatives_and_options(options)
options_with_defaults = DEFAULT_OPTIONS.merge(
options.reject { |k, v| v.nil? }
)
self.alternatives = options_with_defaults[:alternatives]
self.goals = options_with_defaults[:goals]
self.resettable = options_with_defaults[:resettable]
self.algorithm = options_with_defaults[:algorithm]
self.metadata = options_with_defaults[:metadata]
end
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
if alts[0].is_a? Hash
alts = alts[0].map { |k, v| { k => v } }
end
end
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration
options[:metadata] = load_metadata_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
@alternatives.reverse.each {|a| Split.redis.lpush(name, a.name)}
goals_collection.save
save_metadata
Split.redis.set(metadata_key, @metadata.to_json) unless @metadata.nil?
else
existing_alternatives = load_alternatives_from_redis
existing_goals = Split::GoalsCollection.new(@name).load_from_redis
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub("/", "--")
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Merge pull request #391 from pakallis/remove-obsolete-code-save-metadata
Remove unecessary code from Experiment#save
<DFF> @@ -86,7 +86,6 @@ module Split
@alternatives.reverse.each {|a| Split.redis.lpush(name, a.name)}
goals_collection.save
save_metadata
- Split.redis.set(metadata_key, @metadata.to_json) unless @metadata.nil?
else
existing_alternatives = load_alternatives_from_redis
existing_goals = Split::GoalsCollection.new(@name).load_from_redis
| 0 | Merge pull request #391 from pakallis/remove-obsolete-code-save-metadata | 1 | .rb | rb | mit | splitrb/split |
10071445 | <NME> experiment.rb
<BEF> # frozen_string_literal: true
module Split
class Experiment
attr_accessor :name
attr_accessor :goals
attr_accessor :alternative_probabilities
attr_accessor :metadata
attr_reader :alternatives
attr_reader :resettable
DEFAULT_OPTIONS = {
resettable: true
}
def self.find(name)
Split.cache(:experiments, name) do
return unless Split.redis.exists?(name)
Experiment.new(name).tap { |exp| exp.load_from_redis }
end
end
def initialize(name, options = {})
options = DEFAULT_OPTIONS.merge(options)
@name = name.to_s
extract_alternatives_from_options(options)
end
def self.finished_key(key)
"#{key}:finished"
end
def set_alternatives_and_options(options)
options_with_defaults = DEFAULT_OPTIONS.merge(
options.reject { |k, v| v.nil? }
)
self.alternatives = options_with_defaults[:alternatives]
self.goals = options_with_defaults[:goals]
self.resettable = options_with_defaults[:resettable]
self.algorithm = options_with_defaults[:algorithm]
self.metadata = options_with_defaults[:metadata]
end
def extract_alternatives_from_options(options)
alts = options[:alternatives] || []
if alts.length == 1
if alts[0].is_a? Hash
alts = alts[0].map { |k, v| { k => v } }
end
end
if alts.empty?
exp_config = Split.configuration.experiment_for(name)
if exp_config
alts = load_alternatives_from_configuration
options[:goals] = Split::GoalsCollection.new(@name).load_from_configuration
options[:metadata] = load_metadata_from_configuration
options[:resettable] = exp_config[:resettable]
options[:algorithm] = exp_config[:algorithm]
end
end
options[:alternatives] = alts
set_alternatives_and_options(options)
# calculate probability that each alternative is the winner
@alternative_probabilities = {}
alts
end
def save
validate!
if new_record?
start unless Split.configuration.start_manually
persist_experiment_configuration
elsif experiment_configuration_has_changed?
reset unless Split.configuration.reset_manually
persist_experiment_configuration
@alternatives.reverse.each {|a| Split.redis.lpush(name, a.name)}
goals_collection.save
save_metadata
Split.redis.set(metadata_key, @metadata.to_json) unless @metadata.nil?
else
existing_alternatives = load_alternatives_from_redis
existing_goals = Split::GoalsCollection.new(@name).load_from_redis
def validate!
if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
raise ExperimentNotFound.new("Experiment #{@name} not found")
end
@alternatives.each { |a| a.validate! }
goals_collection.validate!
end
def new_record?
ExperimentCatalog.find(name).nil?
end
def ==(obj)
self.name == obj.name
end
def [](name)
alternatives.find { |a| a.name == name }
end
def algorithm
@algorithm ||= Split.configuration.algorithm
end
def algorithm=(algorithm)
@algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
end
def resettable=(resettable)
@resettable = resettable.is_a?(String) ? resettable == "true" : resettable
end
def alternatives=(alts)
@alternatives = alts.map do |alternative|
if alternative.kind_of?(Split::Alternative)
alternative
else
Split::Alternative.new(alternative, @name)
end
end
end
def winner
Split.cache(:experiment_winner, name) do
experiment_winner = redis.hget(:experiment_winner, name)
if experiment_winner
Split::Alternative.new(experiment_winner, name)
else
nil
end
end
end
def has_winner?
return @has_winner if defined? @has_winner
@has_winner = !winner.nil?
end
def winner=(winner_name)
redis.hset(:experiment_winner, name, winner_name.to_s)
@has_winner = true
Split.configuration.on_experiment_winner_choose.call(self)
end
def participant_count
alternatives.inject(0) { |sum, a| sum + a.participant_count }
end
def control
alternatives.first
end
def reset_winner
redis.hdel(:experiment_winner, name)
@has_winner = false
Split::Cache.clear_key(@name)
end
def start
redis.hset(:experiment_start_times, @name, Time.now.to_i)
end
def start_time
Split.cache(:experiment_start_times, @name) do
t = redis.hget(:experiment_start_times, @name)
if t
# Check if stored time is an integer
if t =~ /^[-+]?[0-9]+$/
Time.at(t.to_i)
else
Time.parse(t)
end
end
end
end
def next_alternative
winner || random_alternative
end
def random_alternative
if alternatives.length > 1
algorithm.choose_alternative(self)
else
alternatives.first
end
end
def version
@version ||= (redis.get("#{name}:version").to_i || 0)
end
def increment_version
@version = redis.incr("#{name}:version")
end
def key
if version.to_i > 0
"#{name}:#{version}"
else
name
end
end
def goals_key
"#{name}:goals"
end
def finished_key
self.class.finished_key(key)
end
def metadata_key
"#{name}:metadata"
end
def resettable?
resettable
end
def reset
Split.configuration.on_before_experiment_reset.call(self)
Split::Cache.clear_key(@name)
alternatives.each(&:reset)
reset_winner
Split.configuration.on_experiment_reset.call(self)
increment_version
end
def delete
Split.configuration.on_before_experiment_delete.call(self)
if Split.configuration.start_manually
redis.hdel(:experiment_start_times, @name)
end
reset_winner
redis.srem(:experiments, name)
remove_experiment_cohorting
remove_experiment_configuration
Split.configuration.on_experiment_delete.call(self)
increment_version
end
def delete_metadata
redis.del(metadata_key)
end
def load_from_redis
exp_config = redis.hgetall(experiment_config_key)
options = {
resettable: exp_config["resettable"],
algorithm: exp_config["algorithm"],
alternatives: load_alternatives_from_redis,
goals: Split::GoalsCollection.new(@name).load_from_redis,
metadata: load_metadata_from_redis
}
set_alternatives_and_options(options)
end
def calc_winning_alternatives
# Cache the winning alternatives so we recalculate them once per the specified interval.
intervals_since_epoch =
Time.now.utc.to_i / Split.configuration.winning_alternative_recalculation_interval
if self.calc_time != intervals_since_epoch
if goals.empty?
self.estimate_winning_alternative
else
goals.each do |goal|
self.estimate_winning_alternative(goal)
end
end
self.calc_time = intervals_since_epoch
self.save
end
end
def estimate_winning_alternative(goal = nil)
# initialize a hash of beta distributions based on the alternatives' conversion rates
beta_params = calc_beta_params(goal)
winning_alternatives = []
Split.configuration.beta_probability_simulations.times do
# calculate simulated conversion rates from the beta distributions
simulated_cr_hash = calc_simulated_conversion_rates(beta_params)
winning_alternative = find_simulated_winner(simulated_cr_hash)
# push the winning pair to the winning_alternatives array
winning_alternatives.push(winning_alternative)
end
winning_counts = count_simulated_wins(winning_alternatives)
@alternative_probabilities = calc_alternative_probabilities(winning_counts, Split.configuration.beta_probability_simulations)
write_to_alternatives(goal)
self.save
end
def write_to_alternatives(goal = nil)
alternatives.each do |alternative|
alternative.set_p_winner(@alternative_probabilities[alternative], goal)
end
end
def calc_alternative_probabilities(winning_counts, number_of_simulations)
alternative_probabilities = {}
winning_counts.each do |alternative, wins|
alternative_probabilities[alternative] = wins / number_of_simulations.to_f
end
alternative_probabilities
end
def count_simulated_wins(winning_alternatives)
# initialize a hash to keep track of winning alternative in simulations
winning_counts = {}
alternatives.each do |alternative|
winning_counts[alternative] = 0
end
# count number of times each alternative won, calculate probabilities, place in hash
winning_alternatives.each do |alternative|
winning_counts[alternative] += 1
end
winning_counts
end
def find_simulated_winner(simulated_cr_hash)
# figure out which alternative had the highest simulated conversion rate
winning_pair = ["", 0.0]
simulated_cr_hash.each do |alternative, rate|
if rate > winning_pair[1]
winning_pair = [alternative, rate]
end
end
winner = winning_pair[0]
winner
end
def calc_simulated_conversion_rates(beta_params)
simulated_cr_hash = {}
# create a hash which has the conversion rate pulled from each alternative's beta distribution
beta_params.each do |alternative, params|
alpha = params[0]
beta = params[1]
simulated_conversion_rate = Split::Algorithms.beta_distribution_rng(alpha, beta)
simulated_cr_hash[alternative] = simulated_conversion_rate
end
simulated_cr_hash
end
def calc_beta_params(goal = nil)
beta_params = {}
alternatives.each do |alternative|
conversions = goal.nil? ? alternative.completed_count : alternative.completed_count(goal)
alpha = 1 + conversions
beta = 1 + alternative.participant_count - conversions
params = [alpha, beta]
beta_params[alternative] = params
end
beta_params
end
def calc_time=(time)
redis.hset(experiment_config_key, :calc_time, time)
end
def calc_time
redis.hget(experiment_config_key, :calc_time).to_i
end
def jstring(goal = nil)
js_id = if goal.nil?
name
else
name + "-" + goal
end
js_id.gsub("/", "--")
end
def cohorting_disabled?
@cohorting_disabled ||= begin
value = redis.hget(experiment_config_key, :cohorting)
value.nil? ? false : value.downcase == "true"
end
end
def disable_cohorting
@cohorting_disabled = true
redis.hset(experiment_config_key, :cohorting, true.to_s)
end
def enable_cohorting
@cohorting_disabled = false
redis.hset(experiment_config_key, :cohorting, false.to_s)
end
protected
def experiment_config_key
"experiment_configurations/#{@name}"
end
def load_metadata_from_configuration
Split.configuration.experiment_for(@name)[:metadata]
end
def load_metadata_from_redis
meta = redis.get(metadata_key)
JSON.parse(meta) unless meta.nil?
end
def load_alternatives_from_configuration
alts = Split.configuration.experiment_for(@name)[:alternatives]
raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
if alts.is_a?(Hash)
alts.keys
else
alts.flatten
end
end
def load_alternatives_from_redis
alternatives = redis.lrange(@name, 0, -1)
alternatives.map do |alt|
alt = begin
JSON.parse(alt)
rescue
alt
end
Split::Alternative.new(alt, @name)
end
end
private
def redis
Split.redis
end
def redis_interface
RedisInterface.new
end
def persist_experiment_configuration
redis_interface.add_to_set(:experiments, name)
redis_interface.persist_list(name, @alternatives.map { |alt| { alt.name => alt.weight }.to_json })
goals_collection.save
if @metadata
redis.set(metadata_key, @metadata.to_json)
else
delete_metadata
end
end
def remove_experiment_configuration
@alternatives.each(&:delete)
goals_collection.delete
delete_metadata
redis.del(@name)
end
def experiment_configuration_has_changed?
existing_experiment = Experiment.find(@name)
existing_experiment.alternatives.map(&:to_s) != @alternatives.map(&:to_s) ||
existing_experiment.goals != @goals ||
existing_experiment.metadata != @metadata
end
def goals_collection
Split::GoalsCollection.new(@name, @goals)
end
def remove_experiment_cohorting
@cohorting_disabled = false
redis.hdel(experiment_config_key, :cohorting)
end
end
end
<MSG> Merge pull request #391 from pakallis/remove-obsolete-code-save-metadata
Remove unecessary code from Experiment#save
<DFF> @@ -86,7 +86,6 @@ module Split
@alternatives.reverse.each {|a| Split.redis.lpush(name, a.name)}
goals_collection.save
save_metadata
- Split.redis.set(metadata_key, @metadata.to_json) unless @metadata.nil?
else
existing_alternatives = load_alternatives_from_redis
existing_goals = Split::GoalsCollection.new(@name).load_from_redis
| 0 | Merge pull request #391 from pakallis/remove-obsolete-code-save-metadata | 1 | .rb | rb | mit | splitrb/split |
10071446 | <NME> models.py
<BEF> import os
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
OS_NAMES = (
("aix", "AIX"),
("beos", "BeOS"),
("debian", "Debian Linux"),
("dos", "DOS"),
("freebsd", "FreeBSD"),
("hpux", "HP/UX"),
("mac", "Mac System x."),
("macos", "MacOS X"),
("mandrake", "Mandrake Linux"),
("netbsd", "NetBSD"),
("openbsd", "OpenBSD"),
("qnx", "QNX"),
("redhat", "RedHat Linux"),
("solaris", "SUN Solaris"),
("suse", "SuSE Linux"),
("yellowdog", "Yellow Dog Linux"),
)
ARCHITECTURES = (
("alpha", "Alpha"),
("hppa", "HPPA"),
("ix86", "Intel"),
("powerpc", "PowerPC"),
("sparc", "Sparc"),
("ultrasparc", "UltraSparc"),
)
UPLOAD_TO = getattr(settings,
"DJANGOPYPI_RELEASE_UPLOAD_TO", 'dist')
class Classifier(models.Model):
name = models.CharField(max_length=255, unique=True)
class Meta:
verbose_name = _(u"classifier")
verbose_name_plural = _(u"classifiers")
def __unicode__(self):
return self.name
class Project(models.Model):
name = models.CharField(max_length=255, unique=True)
license = models.TextField(blank=True)
metadata_version = models.CharField(max_length=64, default=1.0)
author = models.CharField(max_length=128, blank=True)
home_page = models.URLField(verify_exists=False, blank=True, null=True)
download_url = models.CharField(max_length=200, blank=True, null=True)
summary = models.TextField(blank=True)
description = models.TextField(blank=True)
author_email = models.CharField(max_length=255, blank=True)
classifiers = models.ManyToManyField(Classifier)
owner = models.ForeignKey(User, related_name="projects")
updated = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _(u"project")
verbose_name_plural = _(u"projects")
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('djangopypi-show_links', (), {'dist_name': self.name})
@models.permalink
def get_pypi_absolute_url(self):
return ('djangopypi-pypi_show_links', (), {'dist_name': self.name})
class Project(models.Model):
name = models.CharField(max_length=255, unique=True)
license = models.CharField(max_length=255, blank=True)
metadata_version = models.CharField(max_length=64, default=1.0)
author = models.CharField(max_length=128, blank=True)
home_page = models.URLField(verify_exists=False, blank=True, null=True)
class Release(models.Model):
version = models.CharField(max_length=32)
distribution = models.FileField(upload_to=UPLOAD_TO)
md5_digest = models.CharField(max_length=255, blank=True)
platform = models.CharField(max_length=128, blank=True)
signature = models.CharField(max_length=128, blank=True)
filetype = models.CharField(max_length=255, blank=True)
pyversion = models.CharField(max_length=32, blank=True)
project = models.ForeignKey(Project, related_name="releases")
upload_time = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _(u"release")
verbose_name_plural = _(u"releases")
unique_together = ("project", "version", "platform", "distribution", "pyversion")
def __unicode__(self):
return u"%s (%s)" % (self.release_name, self.platform)
@property
def type(self):
dist_file_types = {
'sdist':'Source',
'bdist_dumb':'"dumb" binary',
'bdist_rpm':'RPM',
'bdist_wininst':'MS Windows installer',
'bdist_egg':'Python Egg',
'bdist_dmg':'OS X Disk Image'}
return dist_file_types.get(self.filetype, self.filetype)
@property
def filename(self):
return os.path.basename(self.distribution.name)
@property
def release_name(self):
return u"%s-%s" % (self.project.name, self.version)
@property
def path(self):
return self.distribution.name
@models.permalink
def get_absolute_url(self):
return ('djangopypi-show_version', (), {'dist_name': self.project, 'version': self.version})
def get_dl_url(self):
return "%s#md5=%s" % (self.distribution.url, self.md5_digest)
<MSG> Change Release.license to TextField (someone seems to be sending their whole LICENSE.txt file!)
<DFF> @@ -77,7 +77,7 @@ class Classifier(models.Model):
class Project(models.Model):
name = models.CharField(max_length=255, unique=True)
- license = models.CharField(max_length=255, blank=True)
+ license = models.TextField(blank=True)
metadata_version = models.CharField(max_length=64, default=1.0)
author = models.CharField(max_length=128, blank=True)
home_page = models.URLField(verify_exists=False, blank=True, null=True)
| 1 | Change Release.license to TextField (someone seems to be sending their whole LICENSE.txt file!) | 1 | .py | py | bsd-3-clause | ask/chishop |
10071447 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
self.should_receive(:some_method)
finished(@experiment_name)
end
end
end
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Only trigger completion callback with valid Trial
Previously it was possible to trigger the #on_trial_complete even if the Trial
wasn't legally completed (eg #complete! was falsey). This can occur if the user
reaches a #finished call before they reach an #ab_test call.
<DFF> @@ -261,6 +261,12 @@ describe Split::Helper do
self.should_receive(:some_method)
finished(@experiment_name)
end
+
+ it "should not call the method without alternative" do
+ ab_user[@experiment.key] = nil
+ self.should_not_receive(:some_method)
+ finished(@experiment_name)
+ end
end
end
| 6 | Only trigger completion callback with valid Trial | 0 | .rb | rb | mit | splitrb/split |
10071448 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
self.should_receive(:some_method)
finished(@experiment_name)
end
end
end
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Only trigger completion callback with valid Trial
Previously it was possible to trigger the #on_trial_complete even if the Trial
wasn't legally completed (eg #complete! was falsey). This can occur if the user
reaches a #finished call before they reach an #ab_test call.
<DFF> @@ -261,6 +261,12 @@ describe Split::Helper do
self.should_receive(:some_method)
finished(@experiment_name)
end
+
+ it "should not call the method without alternative" do
+ ab_user[@experiment.key] = nil
+ self.should_not_receive(:some_method)
+ finished(@experiment_name)
+ end
end
end
| 6 | Only trigger completion callback with valid Trial | 0 | .rb | rb | mit | splitrb/split |
10071449 | <NME> helper_spec.rb
<BEF> # frozen_string_literal: true
require "spec_helper"
# TODO change some of these tests to use Rack::Test
describe Split::Helper do
include Split::Helper
let(:experiment) {
Split::ExperimentCatalog.find_or_create("link_color", "blue", "red")
}
describe "ab_test" do
it "should not raise an error when passed strings for alternatives" do
expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error
end
it "should not raise an error when passed an array for alternatives" do
expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error
end
it "should raise the appropriate error when passed integers for alternatives" do
expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError)
end
it "should raise the appropriate error when passed symbols for alternatives" do
expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError)
end
it "should not raise error when passed an array for goals" do
expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error
end
it "should not raise error when passed just one goal" do
expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error
end
it "raises an appropriate error when processing combined expirements" do
Split.configuration.experiments = {
combined_exp_1: {
alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ],
metric: :my_metric,
combined_experiments: [:combined_exp_1_sub_1]
}
}
Split::ExperimentCatalog.find_or_create("combined_exp_1")
expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do
ab_test("link_color", "blue", "red")
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should increment the participation counter after assignment to a new user" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1)
end
it "should not increment the counter for an experiment that the user is not participating in" do
ab_test("link_color", "blue", "red")
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
# User shouldn't participate in this second experiment
ab_test("button_size", "small", "big")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should not increment the counter for an not started experiment" do
expect(Split.configuration).to receive(:start_manually).and_return(true)
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
expect {
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
}.not_to change { e.participant_count }
end
it "should return the given alternative for an existing user" do
expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red")
end
it "should always return the winner if one is present" do
experiment.winner = "orange"
expect(ab_test("link_color", "blue", "red")).to eq("orange")
end
it "should allow the alternative to be forced by passing it in the params" do
# ?ab_test[link_color]=blue
@params = { "ab_test" => { "link_color" => "blue" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
@params = { "ab_test" => { "link_color" => "red" } }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1)
expect(alternative).to eq("red")
end
it "should not allow an arbitrary alternative" do
@params = { "ab_test" => { "link_color" => "pink" } }
alternative = ab_test("link_color", "blue")
expect(alternative).to eq("blue")
end
it "should not store the split when a param forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do
@params = { "SPLIT_DISABLE" => "true" }
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq("blue")
alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5)
expect(alternative).to eq("blue")
alternative = ab_test("link_color", "red", "blue")
expect(alternative).to eq("red")
alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1)
expect(alternative).to eq("red")
end
it "should not store the split when Split generically disabled" do
@params = { "SPLIT_DISABLE" => "true" }
expect(ab_user).not_to receive(:[]=)
ab_test("link_color", "blue", "red")
end
context "when store_override is set" do
before { Split.configuration.store_override = true }
it "should store the forced alternative" do
@params = { "ab_test" => { "link_color" => "blue" } }
expect(ab_user).to receive(:[]=).with("link_color", "blue")
ab_test("link_color", "blue", "red")
end
end
context "when on_trial_choose is set" do
before { Split.configuration.on_trial_choose = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_test("link_color", "blue", "red")
end
end
it "should allow passing a block" do
alt = ab_test("link_color", "blue", "red")
ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" }
expect(ret).to eq("shared/#{alt}")
end
it "should allow the share of visitors see an alternative to be specified" do
ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })
expect(["red", "blue"]).to include(ab_user["link_color"])
end
it "should allow alternative weighting interface as a single hash" do
ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"])
expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2])
end
it "should only let a user participate in one experiment at a time" do
link_color = ab_test("link_color", "blue", "red")
ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
big = Split::Alternative.new("big", "button_size")
expect(big.participant_count).to eq(0)
small = Split::Alternative.new("small", "button_size")
expect(small.participant_count).to eq(0)
end
it "should let a user participate in many experiment with allow_multiple_experiments option" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
link_color = ab_test("link_color", "blue", "red")
button_size = ab_test("button_size", "small", "big")
expect(ab_user["link_color"]).to eq(link_color)
expect(ab_user["button_size"]).to eq(button_size)
button_size_alt = Split::Alternative.new(button_size, "button_size")
expect(button_size_alt.participant_count).to eq(1)
end
context "with allow_multiple_experiments = 'control'" do
it "should let a user participate in many experiment with one non-'control' alternative" do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
groups = 100.times.map do |n|
ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n })
end
experiments = ab_user.active_experiments
expect(experiments.size).to be > 1
count_control = experiments.values.count { |g| g == "control" }
expect(count_control).to eq(experiments.size - 1)
count_alts = groups.count { |g| g != "control" }
expect(count_alts).to eq(1)
end
context "when user already has experiment" do
let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) }
before do
Split.configure do |config|
config.allow_multiple_experiments = "control"
end
Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save
Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save
end
it "should restore previously selected alternative" do
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "should select the correct alternatives after experiment resets" do
experiment = Split::ExperimentCatalog.find(:test_0)
experiment.reset
mock_user[experiment.key] = "test-alt"
expect(ab_user.active_experiments.size).to eq 1
expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt"
expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt"
end
it "lets override existing choice" do
pending "this requires user store reset on first call not depending on whelther it is current trial"
self.should_receive(:some_method)
finished(@experiment_name)
end
end
end
ab_test("link_color", "blue", "red")
expect(ab_user).to eq(finished_session)
end
end
describe "metadata" do
context "is defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: { "one" => "Meta1", "two" => "Meta2" }
}
}
end
it "should be passed to helper block" do
@params = { "ab_test" => { "my_experiment" => "two" } }
expect(ab_test("my_experiment")).to eq "two"
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq("Meta2")
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment")).to eq "one"
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq("Meta1")
end
end
context "is not defined" do
before do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
metadata: nil
}
}
end
it "should be passed to helper block" do
expect(ab_test("my_experiment") do |alternative, meta|
meta
end).to eq({})
end
it "should pass control metadata helper block if library disabled" do
Split.configure do |config|
config.enabled = false
end
expect(ab_test("my_experiment") do |_, meta|
meta
end).to eq({})
end
end
end
describe "ab_finished" do
context "for an experiment that the user participates in" do
before(:each) do
@experiment_name = "link_color"
@alternatives = ["blue", "red"]
@experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives)
@alternative_name = ab_test(@experiment_name, *@alternatives)
@previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
end
it "should increment the counter for the completed alternative" do
ab_finished(@experiment_name)
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should set experiment's finished key if reset is false" do
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should not increment the counter if reset is false and the experiment has been already finished" do
2.times { ab_finished(@experiment_name, { reset: false }) }
new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count
expect(new_completion_count).to eq(@previous_completion_count + 1)
end
it "should not increment the counter for an ended experiment" do
e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big")
e.winner = "small"
a = ab_test("button_size", "small", "big")
expect(a).to eq("small")
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new(a, "button_size").completed_count }
end
it "should clear out the user's participation from their session" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should not clear out the users session if reset is false" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name, { reset: false })
expect(ab_user[@experiment.key]).to eq(@alternative_name)
expect(ab_user[@experiment.finished_key]).to eq(true)
end
it "should reset the users session when experiment is not versioned" do
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
it "should reset the users session when experiment is versioned" do
@experiment.increment_version
@alternative_name = ab_test(@experiment_name, *@alternatives)
expect(ab_user[@experiment.key]).to eq(@alternative_name)
ab_finished(@experiment_name)
expect(ab_user.keys).to be_empty
end
context "when on_trial_complete is set" do
before { Split.configuration.on_trial_complete = :some_method }
it "should call the method" do
expect(self).to receive(:some_method)
ab_finished(@experiment_name)
end
it "should not call the method without alternative" do
ab_user[@experiment.key] = nil
expect(self).not_to receive(:some_method)
ab_finished(@experiment_name)
end
end
end
context "for an experiment that the user is excluded from" do
before do
alternative = ab_test("link_color", "blue", "red")
expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1)
alternative = ab_test("button_size", "small", "big")
expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0)
end
it "should not increment the completed counter" do
# So, user should be participating in the link_color experiment and
# receive the control for button_size. As the user is not participating in
# the button size experiment, finishing it should not increase the
# completion count for that alternative.
expect {
ab_finished("button_size")
}.not_to change { Split::Alternative.new("small", "button_size").completed_count }
end
end
context "for an experiment that the user does not participate in" do
before do
Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt")
end
it "should not raise an exception" do
expect { ab_finished(:not_started_experiment) }.not_to raise_exception
end
it "should not change the user state when reset is false" do
expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([])
end
it "should not change the user state when reset is true" do
expect(self).not_to receive(:reset!)
ab_finished(:not_started_experiment)
end
it "should not increment the completed counter" do
ab_finished(:not_started_experiment)
expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0)
expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0)
end
end
end
context "finished with config" do
it "passes reset option" do
Split.configuration.experiments = {
my_experiment: {
alternatives: ["one", "two"],
resettable: false,
}
}
alternative = ab_test(:my_experiment)
experiment = Split::ExperimentCatalog.find :my_experiment
ab_finished :my_experiment
expect(ab_user[experiment.key]).to eq(alternative)
expect(ab_user[experiment.finished_key]).to eq(true)
end
end
context "finished with metric name" do
before { Split.configuration.experiments = {} }
before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original }
def should_finish_experiment(experiment_name, should_finish = true)
alts = Split.configuration.experiments[experiment_name][:alternatives]
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts)
alt_name = ab_user[experiment.key] = alts.first
alt = double("alternative")
expect(alt).to receive(:name).at_most(1).times.and_return(alt_name)
expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt)
if should_finish
expect(alt).to receive(:increment_completion).at_most(1).times
else
expect(alt).not_to receive(:increment_completion)
end
end
it "completes the test" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
metric: :my_metric
}
should_finish_experiment :my_experiment
ab_finished :my_metric
end
it "completes all relevant tests" do
Split.configuration.experiments = {
exp_1: {
alternatives: [ "1-1", "1-2" ],
metric: :my_metric
},
exp_2: {
alternatives: [ "2-1", "2-2" ],
metric: :another_metric
},
exp_3: {
alternatives: [ "3-1", "3-2" ],
metric: :my_metric
},
}
should_finish_experiment :exp_1
should_finish_experiment :exp_2, false
should_finish_experiment :exp_3
ab_finished :my_metric
end
it "passes reset option" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
resettable: false,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
it "passes through options" do
Split.configuration.experiments = {
my_exp: {
alternatives: ["one", "two"],
metric: :my_metric,
}
}
alternative_name = ab_test(:my_exp)
exp = Split::ExperimentCatalog.find :my_exp
ab_finished :my_metric, reset: false
expect(ab_user[exp.key]).to eq(alternative_name)
expect(ab_user[exp.finished_key]).to be_truthy
end
end
describe "conversions" do
it "should return a conversion rate for an alternative" do
alternative_name = ab_test("link_color", "blue", "red")
previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(previous_convertion_rate).to eq(0.0)
ab_finished("link_color")
new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate
expect(new_convertion_rate).to eq(1.0)
end
end
describe "active experiments" do
it "should show an active test" do
alternative = ab_test("def", "4", "5", "6")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show a finished test" do
alternative = ab_test("def", "4", "5", "6")
ab_finished("def", { reset: false })
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "def"
expect(active_experiments.first[1]).to eq alternative
end
it "should show an active test when an experiment is on a later version" do
experiment.reset
expect(experiment.version).to eq(1)
ab_test("link_color", "blue", "red")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "link_color"
end
it "should show versioned tests properly" do
10.times { experiment.reset }
alternative = ab_test(experiment.name, "blue", "red")
ab_finished(experiment.name, reset: false)
expect(experiment.version).to eq(10)
expect(active_experiments.count).to eq 1
expect(active_experiments).to eq({ "link_color" => alternative })
end
it "should show multiple tests" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
alternative = ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 2
expect(active_experiments["def"]).to eq alternative
expect(active_experiments["ghi"]).to eq another_alternative
end
it "should not show tests with winners" do
Split.configure do |config|
config.allow_multiple_experiments = true
end
e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6")
e.winner = "4"
ab_test("def", "4", "5", "6")
another_alternative = ab_test("ghi", "7", "8", "9")
expect(active_experiments.count).to eq 1
expect(active_experiments.first[0]).to eq "ghi"
expect(active_experiments.first[1]).to eq another_alternative
end
end
describe "when user is a robot" do
before(:each) do
@request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)")
end
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not create a experiment" do
ab_test("link_color", "blue", "red")
expect(Split::Experiment.new("link_color")).to be_a_new_record
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when providing custom ignore logic" do
context "using a proc to configure custom logic" do
before(:each) do
Split.configure do |c|
c.ignore_filter = proc { |request| true } # ignore everything
end
end
it "ignores the ab_test" do
ab_test("link_color", "blue", "red")
red_count = Split::Alternative.new("red", "link_color").participant_count
blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((red_count + blue_count)).to be(0)
end
end
end
shared_examples_for "a disabled test" do
describe "ab_test" do
it "should return the control" do
alternative = ab_test("link_color", "blue", "red")
expect(alternative).to eq experiment.control.name
end
it "should not increment the participation count" do
previous_red_count = Split::Alternative.new("red", "link_color").participant_count
previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count
ab_test("link_color", "blue", "red")
new_red_count = Split::Alternative.new("red", "link_color").participant_count
new_blue_count = Split::Alternative.new("blue", "link_color").participant_count
expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count)
end
end
describe "finished" do
it "should not increment the completed count" do
alternative_name = ab_test("link_color", "blue", "red")
previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
ab_finished("link_color")
new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count
expect(new_completion_count).to eq(previous_completion_count)
end
end
end
describe "when ip address is ignored" do
context "individually" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.130")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it_behaves_like "a disabled test"
end
context "for a range" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.129")
Split.configure do |c|
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "using both a range and a specific value" do
before(:each) do
@request = OpenStruct.new(ip: "81.19.48.128")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/
end
end
it_behaves_like "a disabled test"
end
context "when ignored other address" do
before do
@request = OpenStruct.new(ip: "1.1.1.1")
Split.configure do |c|
c.ignore_ip_addresses << "81.19.48.130"
end
end
it "works as usual" do
alternative_name = ab_test("link_color", "red", "blue")
expect {
ab_finished("link_color")
}.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1)
end
end
end
describe "when user is previewing" do
before(:each) do
@request = OpenStruct.new(headers: { "x-purpose" => "preview" })
end
it_behaves_like "a disabled test"
end
describe "versioned experiments" do
it "should use version zero if no version is present" do
alternative_name = ab_test("link_color", "blue", "red")
expect(experiment.version).to eq(0)
expect(ab_user["link_color"]).to eq(alternative_name)
end
it "should save the version of the experiment to the session" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
end
it "should load the experiment even if the version is not 0" do
experiment.reset
expect(experiment.version).to eq(1)
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(alternative_name)
return_alternative_name = ab_test("link_color", "blue", "red")
expect(return_alternative_name).to eq(alternative_name)
end
it "should reset the session of a user on an older version of the experiment" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
new_alternative = Split::Alternative.new(new_alternative_name, "link_color")
expect(new_alternative.participant_count).to eq(1)
end
it "should cleanup old versions of experiments from the session" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(1)
experiment.reset
expect(experiment.version).to eq(1)
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.participant_count).to eq(0)
new_alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color:1"]).to eq(new_alternative_name)
end
it "should only count completion of users on the current version" do
alternative_name = ab_test("link_color", "blue", "red")
expect(ab_user["link_color"]).to eq(alternative_name)
Split::Alternative.new(alternative_name, "link_color")
experiment.reset
expect(experiment.version).to eq(1)
ab_finished("link_color")
alternative = Split::Alternative.new(alternative_name, "link_color")
expect(alternative.completed_count).to eq(0)
end
end
context "when redis is not available" do
before(:each) do
expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new)
end
context "and db_failover config option is turned off" do
before(:each) do
Split.configure do |config|
config.db_failover = false
end
end
describe "ab_test" do
it "should raise an exception" do
expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "finished" do
it "should raise an exception" do
expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED)
end
end
describe "disable split testing" do
before(:each) do
Split.configure do |config|
config.enabled = false
end
end
it "should not attempt to connect to redis" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should return control variable" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect { ab_finished("link_color") }.not_to raise_error
end
end
end
context "and db_failover config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover = true
end
end
describe "ab_test" do
it "should not raise an exception" do
expect { ab_test("link_color", "blue", "red") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_test("link_color", "blue", "red")
end
it "should always use first alternative" do
expect(ab_test("link_color", "blue", "red")).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/blue")
end
context "and db_failover_allow_parameter_override config option is turned on" do
before(:each) do
Split.configure do |config|
config.db_failover_allow_parameter_override = true
end
end
context "and given an override parameter" do
it "should use given override instead of the first alternative" do
@params = { "ab_test" => { "link_color" => "red" } }
expect(ab_test("link_color", "blue", "red")).to eq("red")
expect(ab_test("link_color", "blue", "red", "green")).to eq("red")
expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red")
expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red")
expect(ab_test("link_color", "blue", "red") do |alternative|
"shared/#{alternative}"
end).to eq("shared/red")
end
end
end
context "and preloaded config given" do
before do
Split.configuration.experiments[:link_color] = {
alternatives: [ "blue", "red" ],
}
end
it "uses first alternative" do
expect(ab_test(:link_color)).to eq("blue")
end
end
end
describe "finished" do
it "should not raise an exception" do
expect { ab_finished("link_color") }.not_to raise_error
end
it "should call db_failover_on_db_error proc with error as parameter" do
Split.configure do |config|
config.db_failover_on_db_error = proc do |error|
expect(error).to be_a(Errno::ECONNREFUSED)
end
end
expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original
ab_finished("link_color")
end
end
end
end
context "with preloaded config" do
before { Split.configuration.experiments = {} }
it "pulls options from config file" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
ab_test :my_experiment
expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ])
end
it "can be called multiple times" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: ["goal1", "goal2"]
}
5.times { ab_test :my_experiment }
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ])
expect(experiment.goals).to eq([ "goal1", "goal2" ])
expect(experiment.participant_count).to eq(1)
end
it "accepts multiple goals" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ],
goals: [ "goal1", "goal2", "goal3" ]
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ])
end
it "allow specifying goals to be optional" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "other_opt" ]
}
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.goals).to eq([])
end
it "accepts multiple alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [ "control_opt", "second_opt", "third_opt" ],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ])
end
it "accepts probability on alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 67 },
{ name: "second_opt", percent: 10 },
{ name: "third_opt", percent: 23 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]])
end
it "accepts probability on some alternatives" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt", percent: 34 },
"second_opt",
{ name: "third_opt", percent: 23 },
"fourth_opt",
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "allows name param without probability" do
Split.configuration.experiments[:my_experiment] = {
alternatives: [
{ name: "control_opt" },
"second_opt",
{ name: "third_opt", percent: 64 },
],
}
ab_test :my_experiment
experiment = Split::Experiment.new(:my_experiment)
names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] }
expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]])
expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0)
end
it "fails gracefully if config is missing experiment" do
Split.configuration.experiments = { other_experiment: { foo: "Bar" } }
expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound)
end
it "fails gracefully if config is missing" do
expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError)
end
it "fails gracefully if config is missing alternatives" do
Split.configuration.experiments[:my_experiment] = { foo: "Bar" }
expect { ab_test :my_experiment }.to raise_error(NoMethodError)
end
end
it "should handle multiple experiments correctly" do
experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red")
ab_test("link_color", "blue", "red")
ab_test("link_color2", "blue", "red")
ab_finished("link_color2")
experiment2.alternatives.each do |alt|
expect(alt.unfinished_count).to eq(0)
end
end
context "with goals" do
before do
@experiment = { "link_color" => ["purchase", "refund"] }
@alternatives = ["blue", "red"]
@experiment_name, @goals = normalize_metric(@experiment)
@goal1 = @goals[0]
@goal2 = @goals[1]
end
it "should normalize experiment" do
expect(@experiment_name).to eq("link_color")
expect(@goals).to eq(["purchase", "refund"])
end
describe "ab_test" do
it "should allow experiment goals interface as a single hash" do
ab_test(@experiment, *@alternatives)
experiment = Split::ExperimentCatalog.find("link_color")
expect(experiment.goals).to eq(["purchase", "refund"])
end
end
describe "ab_finished" do
before do
@alternative_name = ab_test(@experiment, *@alternatives)
end
it "should increment the counter for the specified-goal completed alternative" do
expect { ab_finished({ "link_color" => ["purchase"] }) }
.to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0)
.and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1)
end
end
end
end
<MSG> Only trigger completion callback with valid Trial
Previously it was possible to trigger the #on_trial_complete even if the Trial
wasn't legally completed (eg #complete! was falsey). This can occur if the user
reaches a #finished call before they reach an #ab_test call.
<DFF> @@ -261,6 +261,12 @@ describe Split::Helper do
self.should_receive(:some_method)
finished(@experiment_name)
end
+
+ it "should not call the method without alternative" do
+ ab_user[@experiment.key] = nil
+ self.should_not_receive(:some_method)
+ finished(@experiment_name)
+ end
end
end
| 6 | Only trigger completion callback with valid Trial | 0 | .rb | rb | mit | splitrb/split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.