以下是我的代码示例。
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
由于4
不是nil,我希望expect(4).not_to be_nil
返回true而不是false
。任何人都可以帮忙解释一下吗?
答案 0 :(得分:2)
false
的返回值并不意味着它失败,只是意味着4
不是nil
。如果失败,则会引发错误。
RSpec使用NegativeOperatorMatcher
类来测试not_to
期望值(source code here):
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
所以基本上,它返回false,除非实际值等于期望值,在这种情况下它继续使规范失败(即,没有像not_to
这样的负数匹配器将返回{{1}的情况。 })。