Assertions of Truth in Ruby Tests

I used to write my assertions like this:

refute user.inactive?

Then I joined a team where I was encouraged to write this:

assert_equal true,
assert_equal false, user.inactive?

What? That doesn’t look very nice. That’s doesn’t feel very Ruby. It’s less elegant!

Here’s the thing, though: your unit tests aren’t about being elegant. They’re about guaranteeing correctness. You open the door to some insidious bugs when you test truthiness instead of truth.

  • You might perform an assignment rather than comparing equality.
def active?
  # Should be status == :active
  status = :active
  • You might check the presence of an array, rather than its length.
def has_users?
  # Should be user_list.any?

def user_list

Over time, I’ve gotten used to it. This style still chafes, but not as bugs caused by returning the wrong value from a predicate method.

Respond to this post via e-mail