Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "be_true" and "be true" in RSpec

Can any one please explain me about the difference between be_true and be true in Ruby with simple example. I have also seen be_true and be_false are changed to be_truthy and be_falsey

I have an example where 'be true' worked, but when I tried to use 'be_true' or 'be_truthy' spec failed.

I am using RSpec version 3.1.7

like image 761
Dev Raj Avatar asked Nov 06 '14 12:11

Dev Raj


1 Answers

According to this thread be_true and be_false are now known as be_truthy and be_falsy.

The basic difference between be true and be_truthy or be false and be_falsy is that be_falsy/be_truthy matcher passes if the "expected result"(i.e. any object) is(for be_falsy)/ is not(for be_truthy) nil or false, while on the other hand be true and be false use == for validating your "expected result"(boolean object) to be equal to true/ false.

What it means from rspec expectations' truthiness is:

expect(actual).to be_truthy   # passes if actual is truthy (not nil or false)
expect(actual).to be true     # passes if actual == true
expect(actual).to be_falsy    # passes if actual is falsy (nil or false)
expect(actual).to be false    # passes if actual == false
expect(actual).to be_nil      # passes if actual is nil
expect(actual).to_not be_nil  # passes if actual is not nil

Examples -

For be true and be false:

it { expect(true).to be true }        # passes
it { expect("string").to be true }    # fails
it { expect(nil).to be true }         # fails
it { expect(false).to be true }       # fails

it { expect(false).to be false }      # passes
it { expect("string").to be false}    # fails
it { expect(nil).to be false}         # fails
it { expect(true).to be false}        # fails

For be_truthy and be_falsy:

it { expect(true).to be_truthy }      # passes
it { expect("string").to be_truthy }  # passes
it { expect(nil).to be_truthy }       # fails
it { expect(false).to be_truthy }     # fails

it { expect(false).to be_falsy }      # passes
it { expect(nil).to be_falsy }        # passes
it { expect("string").to be_falsy}    # fails
it { expect(true).to be_falsy }       # fails

You can use any other object as "expected result" at the place of "string" except nil/true/false, because they are already present in the examples shown above.

like image 175
Surya Avatar answered Sep 18 '22 14:09

Surya