Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

testunit

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

require 'test/unit'
assert_equal(5,5)
like image 683
Chris Avatar asked Oct 03 '10 14:10

Chris


3 Answers

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.

like image 164
John Hyland Avatar answered Oct 23 '22 13:10

John Hyland


The Correct answer is ,

require 'test/unit/assertions'

include Test::Unit::Assertions
like image 32
Nilesh Kaingade Avatar answered Oct 23 '22 11:10

Nilesh Kaingade


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.

like image 38
Andrew Grimm Avatar answered Oct 23 '22 12:10

Andrew Grimm