RSpec Matchers: Be careful while testing boolean values

While testing methods that return boolean values in ruby (the ones that end in ‘?’), try to avoid following matchers:

method_returning_true?.should be_true


method_returning_false?should be_false

This is because, ‘be_true’ and ‘be_false’ matchers considers ‘nil’ to be false and anything other than ‘nil’ to be true. When we write methods in ruby which end with question mark (‘?’), intent is that the method will return boolean value. To ensure that our tests will always reflect the intent of code, use following to assert boolean values instead of using ‘be_true’ or ‘be_false’ matchers:

method_returning_true?.should == true


method_returning_false?.should == false


  1. There was an interesting discussion about this just last week at RubyConf in New Orleans. Not so much about RSpec, about Ruby predicates (i.e. methods that end with ‘?’) and “truthiness.” Essentially, nearly all of the time, we write code like this:

    if some_predicate?

    In that example, do_something would be executed if some_predicate? returned any value other than nil or false, so there is no reason to ensure that it is true or false, just that it is “truthy” or “falsy” :)

    That is the reason that RSpec’s be_true and be_false work as they do and unless you have a very good reason to check the explicit value rather than its meaning in the context of the expression, you should probably just use the matchers as they are.

Speak Your Mind