Skip to content

Commit

Permalink
Merge pull request #211 from nickh/nh-after-run
Browse files Browse the repository at this point in the history
Add support for experiment after_run blocks
  • Loading branch information
zerowidth authored Apr 5, 2023
2 parents 5945f33 + 6ea1efc commit 3d05135
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/scientist/experiment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ def before_run(&block)
@_scientist_before_run = block
end

# Define a block of code to run after an experiment completes, if the experiment
# is enabled.
#
# The block takes one argument, the Scientist::Result containing experiment results.
#
# Returns the configured block.
def after_run(&block)
@_scientist_after_run = block
end

# A Hash of behavior blocks, keyed by String name. Register behavior blocks
# with the `try` and `use` methods.
def behaviors
Expand Down Expand Up @@ -230,6 +240,10 @@ def run(name = nil)

result = generate_result(name)

if @_scientist_after_run
@_scientist_after_run.call(result)
end

begin
publish(result)
rescue StandardError => ex
Expand Down
31 changes: 31 additions & 0 deletions test/scientist/experiment_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,37 @@ def @ex.enabled?
end
end

describe "after run block" do
it "runs when an experiment is enabled" do
control_ok = candidate_ok = false
after_result = nil
@ex.after_run { |result| after_result = result }
@ex.use { control_ok = after_result.nil? }
@ex.try { candidate_ok = after_result.nil? }

@ex.run

assert after_result, "after_run should have run"
assert after_result.matched?, "after_run should be called with the result"
assert control_ok, "control should have run before after_run"
assert candidate_ok, "candidate should have run before after_run"
end

it "does not run when an experiment is disabled" do
after_result = nil

def @ex.enabled?
false
end
@ex.after_run { |result| after_result = result }
@ex.use { "value" }
@ex.try { "value" }
@ex.run

refute after_result, "after_run should not have run"
end
end

describe "testing hooks for extending code" do
it "allows a user to provide fabricated durations for testing purposes" do
@ex.use { true }
Expand Down

0 comments on commit 3d05135

Please sign in to comment.