tags:

views:

31

answers:

2

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

require 'test/unit'
assert_equal(5,5)
+4  A: 

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.

John Hyland
This was perfect. Thanks for the quick response. Just needed to remove the quotes after the extend statement.
Chris
Whoops, that's what I get for not testing it out. :-) Fixed and filled in a little more explanation (for you or any future viewers).
John Hyland
If you want it to return true/false in IRB, just use == instead. 5 == 5 # => true 5 == 6 # => false
Jason Noble
A: 

You can also do

raise "Something's gone wrong" unless 5 == 5

I don't use assert in code that's being tested, I only use it in test code.

Andrew Grimm