Class: Whitestone::Assertion::Custom::CustomTestContext

Inherits:
Object
  • Object
show all
Defined in:
lib/whitestone/custom_assertions.rb

Overview

CustomTestContext – an environment in which a custom text can run and have access to its parameters.

Example usage (test writer’s point of view):

Whitestone.custom :circle, {
  :description => "Circle equality",
  :parameters  => [ [:circle, Circle], [:values, Array] ],
  :run => lambda {
    x, y, r, label = values
    test('x')     { Ft x, circle.centre.x         }
    test('y')     { Ft y, circle.centre.y         }
    test('r')     { Ft r, circle.radius           }
    test('label') { Eq Label[label], circle.label }
  }
}

That lambda on Line 4 gets evaluated in a CustomTestContext object, which gives it access to the method ‘test’ and the parameters ‘circle’ and ‘values’, which are dynamically-defined methods on the context object.

Example usage (CustomTestContext user’s point of view):

context = CustomTestContext.new(parameters, arguments)
context.instance_eval(block)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parameters, values) ⇒ CustomTestContext

Example:

parameters: [ [:circle, Circle], [:values, Array] ],
    values: [ circle_object, [4,1,5,:X] ]

Result of calling method:

def circle() circle_object end
def values() [4,1,5,:X]    end

Effect:

  • code run in this context (i.e. with this object as ‘self’) can access the methods ‘circle’ and ‘values’, as well as the method ‘test’.



227
228
229
230
231
232
233
234
235
# File 'lib/whitestone/custom_assertions.rb', line 227

def initialize(parameters, values)
  parameters = parameters.map { |name, type| name }
  parameters.zip(values).each do |param, value|
    metaclass = class << self; self; end
    metaclass.module_eval do
      define_method(param) { value }
    end
  end
end

Instance Attribute Details

#context_labelObject (readonly)

The label associated with the current assertion (see #test).



216
217
218
# File 'lib/whitestone/custom_assertions.rb', line 216

def context_label
  @context_label
end

Instance Method Details

#test(label, &assertion) ⇒ Object

See the example usage above. The block is expected to have a single assertion in it (but of course we can’t control or even check that).

If the assertion fails, we use the label as part of the error message so it’s easy to see what went wrong.

Therefore we save the label so the test runner that is using this context can access it. In the example above, the value of ‘context_label’ at different times throughout the lambda is ‘x’, ‘y’, ‘r’ and ‘label’.



246
247
248
249
# File 'lib/whitestone/custom_assertions.rb', line 246

def test(label, &assertion)
  @context_label = label
  assertion.call
end