Dynamic examples with null context

This commit is contained in:
Michael Miller 2020-11-07 14:43:59 -07:00
parent 40dd85eb38
commit 8ae6ef478b
No known key found for this signature in database
GPG key ID: FB9F12F7C646A4AD
4 changed files with 28 additions and 2 deletions

View file

@ -26,6 +26,17 @@ module Spectator
super(name, source, group)
end
# Creates a dynamic example.
# A block provided to this method will be called as-if it were the test code for the example.
# The block will be given this example instance as an argument.
# The *name* describes the purpose of the example.
# It can be a `Symbol` to describe a type.
# The *source* tracks where the example exists in source code.
# The example will be assigned to *group* if it is provided.
def initialize(name : String? = nil, source : Source? = nil, group : ExampleGroup? = nil, &block : Example -> _)
@delegate = ExampleContextDelegate.null(&block)
end
# Executes the test case.
# Returns the result of the execution.
# The result will also be stored in `#result`.

View file

@ -1,5 +1,6 @@
require "./context"
require "./example_context_method"
require "./null_context"
module Spectator
# Stores a test context and a method to call within it.
@ -11,6 +12,15 @@ module Spectator
def initialize(@context : Context, @method : ExampleContextMethod)
end
# Creates a delegate with a null context.
# The context will be ignored and the block will be executed in its original scope.
# The example instance will be provided as an argument to the block.
def self.null(&block : Example -> _)
context = NullContext.new
method = ExampleContextMethod.new { |example| block.call(example) }
new(context, method)
end
# Invokes a method in the test context.
# The *example* is the current running example.
def call(example : Example)

View file

@ -4,8 +4,7 @@ module Spectator
# Encapsulates a method in a test context.
# This could be used to invoke a test case or hook method.
# The context is passed as an argument.
# The proc should downcast the context instance to the desired type
# and call a method on that context.
# The proc should downcast the context instance to the desired type and call a method on that context.
# The current example is also passed as an argument.
alias ExampleContextMethod = Example, Context ->
end

View file

@ -0,0 +1,6 @@
module Spectator
# Empty context used to construct examples that don't have contexts.
# This is useful for dynamically creating examples outside of a spec.
class NullContext < Context
end
end