From 2c0238d178f702c87637cef46f9e420df5b49e4f Mon Sep 17 00:00:00 2001 From: Michael Miller Date: Mon, 10 Sep 2018 22:33:40 -0600 Subject: [PATCH] Invoke before_each, before_all, after_each, and after_all hooks --- src/spectator/context.cr | 45 ++++++++++++++++++++++++++++++++++++++++ src/spectator/runner.cr | 4 ++++ 2 files changed, 49 insertions(+) diff --git a/src/spectator/context.cr b/src/spectator/context.cr index a391e5f..485eb7e 100644 --- a/src/spectator/context.cr +++ b/src/spectator/context.cr @@ -11,6 +11,9 @@ module Spectator getter after_each_hooks = [] of -> getter around_each_hooks = [] of Example -> + @before_all_hooks_run = false + @after_all_hooks_run = false + def initialize(@parent = nil) if (parent = @parent) parent.contexts << self @@ -21,6 +24,48 @@ module Spectator add_examples end + def run_before_all_hooks + if (parent = @parent) + parent.run_before_all_hooks + end + unless @before_all_hooks_run + @before_all_hooks.each do |hook| + hook.call + end + @before_all_hooks_run = true + end + end + + def run_before_each_hooks + if (parent = @parent) + parent.run_before_each_hooks + end + @before_each_hooks.each do |hook| + hook.call + end + end + + def run_after_all_hooks + unless @after_all_hooks_run + @after_all_hooks.each do |hook| + hook.call + end + @after_all_hooks_run = true + end + if (parent = @parent) + parent.run_after_all_hooks + end + end + + def run_after_each_hooks + @after_each_hooks.each do |hook| + hook.call + end + if (parent = @parent) + parent.run_after_each_hooks + end + end + protected def add_examples(array = [] of Example) array.concat(@examples) contexts.each do |context| diff --git a/src/spectator/runner.cr b/src/spectator/runner.cr index 0258450..3b16bea 100644 --- a/src/spectator/runner.cr +++ b/src/spectator/runner.cr @@ -24,6 +24,8 @@ module Spectator private def run_example(example) error = nil + example.context.run_before_all_hooks + example.context.run_before_each_hooks elapsed = Time.measure do begin example.run @@ -31,6 +33,8 @@ module Spectator error = ex end end + example.context.run_after_each_hooks + example.context.run_after_all_hooks case error when Nil SuccessfulExampleResult.new(example, elapsed)