Class: SolidAssert::Assert

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/solid_assert/assert.rb

Overview

Actual assertions implementation

Instance Method Summary collapse

Instance Method Details

#assert(condition, exception = nil) ⇒ Object

Check if a condition is truthy and fail if it is not.

Usage:

assert expr  # raise SolidAssert::AssertionFailedError if expr is falsy
assert !list.empty?, "The list should not be empty"  # optional error message
assert false, StandardError.new("Not XYZ!")  # raise custom exception object
assert false, CustomError  # raise custom exception class

Parameters:

  • condition

    A condition to assert

  • exception (defaults to: nil)

    An optional error message (or exception)

Raises:



21
22
23
24
25
26
27
28
29
# File 'lib/solid_assert/assert.rb', line 21

def assert(condition, exception = nil)
  if !condition
    if exception.kind_of?(Exception) or exception.class.eql?(Class)
      raise exception
    else
      raise SolidAssert::AssertionFailedError.new(exception)
    end
  end
end

#invariant(exception = nil) { ... } ⇒ Object

Let you #assert a block of code.

It comes handy when your assertion requires more than one line of code. An assertion is performed on the result of the provided block evaluation.

Usage:

invariant do
  some_number = 1
  other_number = 2
  some_number == other_number
end

invariant "Both numbers should be equal" do  # optional error message
  ...
  some_number == other_number
end

invariant CustomError do  # custom exception class
  ...
  some_number == other_number
end

Parameters:

  • exception (defaults to: nil)

    An optional error message (or exception)

Yields:

  • A block of code



55
56
57
# File 'lib/solid_assert/assert.rb', line 55

def invariant(exception = nil)
  assert yield, exception
end