In ruby, can you execute assert_equal and other asserts while in irb?

Chris picture Chris · Oct 3, 2010 · Viewed 11.9k times · Source

Can you execute assert_equal from within irb? This does not work.

require 'test/unit'
assert_equal(5,5)

Answer

John Hyland picture John Hyland · Oct 3, 2010

Sure you can!

require 'test/unit'
extend Test::Unit::Assertions
assert_equal 5, 5                # <= nil
assert_equal 5, 6                # <= raises AssertionFailedError

What's going on is that all the assertions are methods in the Test::Unit::Assertions module. Extending that module from inside irb makes those methods available as class methods on main, which allows you to call them directly from your irb prompt. (Really, calling extend SomeModule in any context will put the methods in that module somewhere you can call them from the same context - main just happens to be where you are by default.)

Also, since the assertions were designed to be run from within a TestCase, the semantics might be a little different than expected: instead of returning true or false, it returns nil or raises an error.