15

I am using rspec and for asserts like

student.name should be nil
student.name should be_nil

Both seem to work. is there a difference between using be nil an be_nil ???

Abid
  • 7,149
  • 9
  • 44
  • 51

2 Answers2

21

There is no difference really, except be nil gets defined on the fly, and be_nil has been specifically programmed by rspec.

when you say should.be something, rspec tries the following

   [:==, :<, :<=, :>=, :>, :===].each do |operator|
      define_method operator do |operand|
        BeComparedTo.new(operand, operator)
      end
    end

Whereas, when you try should.be_nil it just checks

object.nil?

https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/be.rb

DVG
  • 17,392
  • 7
  • 61
  • 88
4

I think there is no difference but it's used for consistency with other methods like be_true or be_false.

Under the hood be checks the id of both elements:

  • works with nil

  • fails with true because in Ruby everything not false nor nil is true

  • fails with false since both nil and false match

apneadiving
  • 114,565
  • 26
  • 219
  • 213