RSpec not_to未显示正确的结果

时间:2014-07-31 12:23:10

标签: 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: 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。任何人都可以帮忙解释一下吗?

1 个答案:

答案 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}的情况。 })。