Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

be false vs be_falsey in rspec [duplicate]

Tags:

ruby

rspec

I know be false will just return true if the expected value is a pure false value, wherease be_falsey will return true if the expected value is either false or nil.

However, I fail to understand when would I use one or the other. I fail to see an example where be_falsey would be more useful than be false.

like image 819
Hommer Smith Avatar asked Oct 23 '25 14:10

Hommer Smith


1 Answers

There are lots of situations in Ruby where you get a nil result and want to treat it like false. For example, suppose we have a method that handles an options hash, and we want the absence of an option to be the same as the option set to false:

def verbose?(opts)
  opts[:verbose]  
end

opts = { verbose: false }
expect(verbose?(opts)).to be_falsey # => PASS

opts = { verbose: true }
expect(verbose?(opts)).to be_falsey # => FAIL

opts = {}
expect(verbose?(opts)).to be_falsey # => PASS

Obviously this is a simplistic example (you could argue that verbose? should always return true or false), but similar scenarios are common in Ruby.

like image 125
Jordan Running Avatar answered Oct 26 '25 08:10

Jordan Running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!