Is anyone aware of a Ruby module that adds support for assertions such as
what is supported in Java 1.4? I wrote such a thing yesterday and am
considering releasing it if I’m not duplicating what someone else has
already done.
I’ve included some examples below showing how mine is used.
When an assertion fails, a stack trace is output, a message describing the
failed assertion is output and execution stops (actually it raises an
AssertionError which typically would not be caught). This is primarily for
use during initial development of new code. Assertions are disabled by
default. To enable them, the global variable $enable_assertions must be set
to true (Should I use some other mechanism besides a global variable to do
this?). Even when assertions are disabled, they provide good documentation
on what your code expects.
···
require ‘Assertions’
$enable_assertions = true
Assert that the value of temperature is in the range 0 to 100.
The first parameter is the condition to be tested (should evaluate to true
or false)
and the last parameter is a description of what is being asserted.
assert((0…100).include?(temperature), “valid temperature returned”)
Assert that the object wsdl responds to the messages “proxy” and
“service”.
The first parameter is the value to be tested and the remaining parameters
are any number of symbols referring to messages.
assert_responds(wsdl, :proxy, :service)
Assert that the object currently referred to by operationName is a kind of
String.
The first parameter is the value to be tested and the
remaining parameters are the allowed types for the value.
assert_type(operationName, String, QName)
Assert that localName is a kind of String, namespace is a kind of String
and
prefix is either a kind of String or is nil.
Each parameter is an array containing a value to be tested
and the types allowed for that value.
NilClass is used to specify that a value can be nil.
assert_types([localName, String],
[namespace, String],
[prefix, String, NilClass])
I understand all the debate over whether checking types in Ruby code is a
good idea. Even if you decide not to use assert_responds, assert_type and
assert_types, using just the assert method to test certain conditions is
useful on its own.
WARNING: All e-mail sent to and from this address will be received or
otherwise recorded by the A.G. Edwards corporate e-mail system and is
subject to archival, monitoring or review by, and/or disclosure to,
someone other than the recipient.