rspec what is the difference between be nil and be_nil

落花浮王杯 提交于 2020-01-03 07:20:23

问题


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 ???


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/10856869/rspec-what-is-the-difference-between-be-nil-and-be-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!