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".
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
I think it is totally valid to use asserts in Ruby. But you are mentioning two different things:
assert
methods for checking your tests expectations. They are intended to be used in your test code, not in your application code.assert
construction intended to be used inside the code of your programs, to check assumptions you make about their integrity. These checks are built inside the code itself. They are not a test-time utility, but a development-time one.I recently wrote solid_assert: a little Ruby library implementing a Ruby assertion utility and also a post in my blog explaining its motivation.. It let you write expressions in the form:
assert some_string != "some value" assert clients.empty?, "Isn't the clients list empty?" invariant "Lists with different sizes?" do one_variable = calculate_some_value other_variable = calculate_some_other_value one_variable > other_variable end
And they can be deactivated so assert
and invariant
get evaluated as empty statements. This let you avoid any performance problem in production. But notice that The Pragmatic Programmers recommend against deactivating them. You should only deactivate them if they really affect to the performance.
Regarding to the answer saying that the idiomatic Ruby way is using a normal raise
statement, I think it lacks of expressivity. One of the golden rules of assertive programming is not using assertions for normal exception handling. They are two completely different things. If you use the same syntax for the two of them, I think you code will be more obscure. And of course you lose the capability of deactivating them.
You can be convinced that using assertions is a good thing because two must-read classic books like The Pragmatic Programmer From Journeyman to Master and Code Complete dedicate whole sections to them and recommend their use. There is also a nice article titled Programming with assertions that illustrate very well what is assertive programming about and when to use it (it is based in Java, but concepts apply to any language).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With