Invoke before_each, before_all, after_each, and after_all hooks

This commit is contained in:
Michael Miller 2018-09-10 22:33:40 -06:00
parent a725c0d5be
commit 2c0238d178
2 changed files with 49 additions and 0 deletions

View file

@ -11,6 +11,9 @@ module Spectator
getter after_each_hooks = [] of -> getter after_each_hooks = [] of ->
getter around_each_hooks = [] of Example -> getter around_each_hooks = [] of Example ->
@before_all_hooks_run = false
@after_all_hooks_run = false
def initialize(@parent = nil) def initialize(@parent = nil)
if (parent = @parent) if (parent = @parent)
parent.contexts << self parent.contexts << self
@ -21,6 +24,48 @@ module Spectator
add_examples add_examples
end 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) protected def add_examples(array = [] of Example)
array.concat(@examples) array.concat(@examples)
contexts.each do |context| contexts.each do |context|

View file

@ -24,6 +24,8 @@ module Spectator
private def run_example(example) private def run_example(example)
error = nil error = nil
example.context.run_before_all_hooks
example.context.run_before_each_hooks
elapsed = Time.measure do elapsed = Time.measure do
begin begin
example.run example.run
@ -31,6 +33,8 @@ module Spectator
error = ex error = ex
end end
end end
example.context.run_after_each_hooks
example.context.run_after_all_hooks
case error case error
when Nil when Nil
SuccessfulExampleResult.new(example, elapsed) SuccessfulExampleResult.new(example, elapsed)