From 1eb5b151236494b08a80813ee0ffc3bc2594f6bc Mon Sep 17 00:00:00 2001 From: Andrii Furmanets Date: Fri, 16 Oct 2026 20:03:06 +0300 Subject: [PATCH] Inherit raise_on_mismatches from the superclass Setting raise_on_mismatches on a base experiment class had no effect on its subclasses, because the flag lives in a class instance variable. Fall back to the superclass when a class hasn't set its own value. Fixes #174 --- README.md | 2 ++ lib/scientist/experiment.rb | 9 ++++++++- test/scientist/experiment_test.rb | 23 +++++++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e076498..59d8481 100644 --- a/README.md +++ b/README.md @@ -405,6 +405,8 @@ end MyExperiment.raise_on_mismatches = true ``` +Subclasses of `MyExperiment` inherit this setting unless they set their own. + Scientist will raise a `Scientist::Experiment::MismatchError` exception if any observations don't match. #### Custom mismatch errors diff --git a/lib/scientist/experiment.rb b/lib/scientist/experiment.rb index 591b3a0..9f0d842 100644 --- a/lib/scientist/experiment.rb +++ b/lib/scientist/experiment.rb @@ -72,8 +72,15 @@ def raise_on_mismatches=(bool) end # Whether or not to raise a mismatch error when a mismatch occurs. + # + # Subclasses inherit the setting from their superclass unless they set + # their own. def raise_on_mismatches? - @raise_on_mismatches + if !@raise_on_mismatches.nil? + @raise_on_mismatches + elsif respond_to?(:superclass) && superclass.respond_to?(:raise_on_mismatches?) + superclass.raise_on_mismatches? + end end end diff --git a/test/scientist/experiment_test.rb b/test/scientist/experiment_test.rb index 434e673..aa00540 100644 --- a/test/scientist/experiment_test.rb +++ b/test/scientist/experiment_test.rb @@ -546,6 +546,29 @@ def @ex.raised(op, exception) assert_raises(Scientist::Experiment::MismatchError) { @ex.run } end + + it "inherits the raise_on_mismatches class attribute from a superclass" do + subclass = Class.new(Fake) + Fake.raise_on_mismatches = true + + ex = subclass.new + ex.use { "fine" } + ex.try { "not fine" } + + assert_raises(Scientist::Experiment::MismatchError) { ex.run } + end + + it "lets a subclass override the raise_on_mismatches class attribute" do + subclass = Class.new(Fake) + Fake.raise_on_mismatches = true + subclass.raise_on_mismatches = false + + ex = subclass.new + ex.use { "fine" } + ex.try { "not fine" } + + assert_equal "fine", ex.run + end end describe "MismatchError" do