Wiki

Assert Statement

The assert statement is used to verify an expected condition during runtime.

Grammar

assert <condition>[, <info>]

If the condition is true, execution proceeds. Otherwise, an AssertException? is raised. Assertions can be turned off at runtime with:

CobraCore.willCheckAssert = false

Assertions are useful for catching errors early when they are easier to diagnose. They also enable subsequent code to operate under the condition expressed by the assertion. Furthermore, they are source of technical documentation.

The message of the AssertException includes information to assist in debugging the assertion including:

  • the filename and line number where the assert statement appeared
  • the info argument, if provided
  • a full breakdown of the condition's subexpressions and their values

The breakdown of the condition is significant because it not only aids troubleshooting, but largely eliminates the need to specify the info argument. For example, rather than:

assert obj.foo > bar, 'obj=[obj], obj.foo=[obj.foo], bar=[bar]'

This is sufficient:

assert obj.foo > bar

...because if the assertion fails, the values of obj, obj.foo and bar will be given in the exception's message. Note that reporting the subexpression values causes the subexpressions to execute a second time, so the reported values can be misleading due to side-effects. In practice, this is rare.

Developers often disable assertions in production software, presumably for a speed boost. But in practice, the overhead of assert statements is often so small as to not be noticeable. Since assertions offer the benefit of easier failure analysis, they should generally be left on. At the same time, providing a switch to turn them off can be prudent because the assertions themselves can be buggy (meaning the assertion fails, but does indicate an actual problem with the program because the condition was poorly formulated).

Strongly consider using require instead of assert when verifying the state of the object at the very beginning of a method or property, or verifying the state of the parameters. Strongly consider using ensure instead of assert when verifying the state of the object at the very ending of a method or property, or verifying the state of the return value.

# Example 1 
assert x > y 

# Example 2 
assert node # as in, the node is not nil 

# Example 3 
assert customers.count # as in, the count is not zero 

# Example 4 
assert name.length