Is it idiomatic Ruby to add an assert( ) method to Ruby's Kernel class?

Viewed 41737

I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it?

BTW, I know of the existence of the various Unit frameworks in Ruby - this is an exercise to learn the Ruby idioms, rather than to "get something done".

5 Answers

No it's not a best practice. The best analogy to assert() in Ruby is just raising

 raise "This is wrong" unless expr

and you can implement your own exceptions if you want to provide for more specific exception handling

What's your reason for adding the assert method to the Kernel module? Why not just use another module called Assertions or something?

Like this:

module Assertions
  def assert(param)
    # do something with param
  end

  # define more assertions here
end

If you really need your assertions to be available everywhere do something like this:

class Object
  include Assertions
end

Disclaimer: I didn't test the code but in principle I would do it like this.

My understanding is that you're writing your own testing suite as a way of becoming more familiar with Ruby. So while Test::Unit might be useful as a guide, it's probably not what you're looking for (because it's already done the job).

That said, python's assert is (to me, at least), more analogous to C's assert(3). It's not specifically designed for unit-tests, rather to catch cases where "this should never happen".

How Ruby's built-in unit tests tend to view the problem, then, is that each individual test case class is a subclass of TestCase, and that includes an "assert" statement which checks the validity of what was passed to it and records it for reporting.

Related