Ruby on rails RSpec not_to未显示正确的结果

Ruby on rails RSpec not_to未显示正确的结果,ruby-on-rails,ruby,testing,rspec,Ruby On Rails,Ruby,Testing,Rspec,下面是我的代码示例 MacBook-Pro:~ hehe$ irb 2.1.2 :001 > require 'rspec/expectations' => true 2.1.2 :002 > include RSpec::Matchers => Object 2.1.2 :003 > expect(4).to be_nil RSpec::Expectations::ExpectationNotMetError: expected: nil got

下面是我的代码示例

MacBook-Pro:~ hehe$ irb
2.1.2 :001 > require 'rspec/expectations'
 => true 
2.1.2 :002 > include RSpec::Matchers
 => Object 
2.1.2 :003 > expect(4).to be_nil
RSpec::Expectations::ExpectationNotMetError: expected: nil
     got: 4
    from /Users/hehe/.rvm/gems/ruby-2.1.2/gems/rspec-expectations-3.0.3/lib/rspec/expectations/fail_with.rb:30:in `fail_with'
    from /Users/hehe/.rvm/gems/ruby-2.1.2/gems/rspec-expectations-3.0.3/lib/rspec/expectations/handler.rb:37:in `handle_failure'
    from /Users/hehe/.rvm/gems/ruby-2.1.2/gems/rspec-expectations-3.0.3/lib/rspec/expectations/handler.rb:48:in `handle_matcher'
    from /Users/hehe/.rvm/gems/ruby-2.1.2/gems/rspec-expectations-3.0.3/lib/rspec/expectations/expectation_target.rb:54:in `to'
    from (irb):3
    from /Users/hehe/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `<main>'
2.1.2 :004 > expect(4).not_to be_nil
 => false
MacBookPro:~hehe$irb
2.1.2:001>要求“rspec/预期”
=>正确
2.1.2:002>包括RSpec::匹配器
=>对象
2.1.2:003>预期(4).为零
RSpec::Expectations::ExpectationNotMetError:预期:无
得到:4
from/Users/hehe/.rvm/gems/ruby-2.1.2/gems/rspec-expectations-3.0.3/lib/rspec/expectations/fail_with.rb:30:in'fail_with'
from/Users/hehe/.rvm/gems/ruby-2.1.2/gems/rspec-expectations-3.0.3/lib/rspec/expectations/handler.rb:37:in“handle\u failure”
from/Users/hehe/.rvm/gems/ruby-2.1.2/gems/rspec-expectations-3.0.3/lib/rspec/expectations/handler.rb:48:in'handle\u matcher'
from/Users/hehe/.rvm/gems/ruby-2.1.2/gems/rspec-expectations-3.0.3/lib/rspec/expectations/expectations\u target.rb:54:in“to”
来自(irb):3
from/Users/hehe/.rvm/rubies/ruby-2.1.2/bin/irb:11:in`'
2.1.2:004>期望(4).不为零
=>错误

因为
4
不是零,我希望
expect(4)。not\u to\u nil
返回true而不是
false
。有人能解释一下吗?

返回值
false
并不意味着它失败,它只是意味着
4
不是
nil
。如果失败,它将引发一个错误

RSpec使用一个
NegativeOperatorMatcher
类来测试
not_to
expections():

class NegativeOperatorMatcher

因此,基本上,除非实际值等于预期值,否则它将返回false,在这种情况下,它将继续不符合规范(即不存在像
not_to
这样的负匹配器将永远返回
true
)。

RSpec不会返回true或false。它的目的是在未达到预期时,通过提出错误来强制测试失败。如果它只是返回false,测试就不会失败。自己尝试一下:编写一个只调用
false
的小测试。考试过去了。如果没有出现错误,而不是最后一条语句的计算结果为true,则测试通过。
class NegativeOperatorMatcher < OperatorMatcher
  def __delegate_operator(actual, operator, expected)
    return false unless actual.__send__(operator, expected)
    fail_with_message("expected not: #{operator} #{expected.inspect}\n         got: #{operator.gsub(/./, ' ')} #{actual.inspect}")
  end
end