Assertions of Truth in Ruby Tests

James - Jan 17 '21 - - Dev Community

I used to write my assertions like this:

assert user.active?
refute user.inactive?
Enter fullscreen mode Exit fullscreen mode

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

assert_equal true, user.active?
assert_equal false, user.inactive?
Enter fullscreen mode Exit fullscreen mode

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
end
Enter fullscreen mode Exit fullscreen mode
  • You might check the presence of an array, rather than its length.
def has_users?
  # Should be user_list.any?
  user_list
end

def user_list
  []
end
Enter fullscreen mode Exit fullscreen mode

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

. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player