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

3

15

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

require 'test/unit'
assert_equal(5,5)
Karly answered 3/10, 2010 at 14:56 Comment(0)
K
35

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.

Kazue answered 3/10, 2010 at 15:4 Comment(3)
This was perfect. Thanks for the quick response. Just needed to remove the quotes after the extend statement.Karly
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).Kazue
If you want it to return true/false in IRB, just use == instead. 5 == 5 # => true 5 == 6 # => falseDownstage
W
9

The Correct answer is ,

require 'test/unit/assertions'

include Test::Unit::Assertions
Webby answered 20/1, 2014 at 11:26 Comment(1)
Wow. great!! after searching all over the internet. I found this solution.@NileshEudoca
U
6

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.

Unemployable answered 3/10, 2010 at 21:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.