【问题标题】:Mocha expect failing with Thor 0.19.1摩卡预计雷神 0.19.1 失败
【发布时间】:2014-04-11 08:31:06
【问题描述】:

将 Thor 从 0.18.1 升级到 0.19.1 后,我看到 Mocha 出现了奇怪的故障(使用测试单元)

/gems/2.1.0/gems/test-unit-2.5.5/lib/test/unit/ui/console/testrunner.rb:395:
  in `output': unexpected invocation: #<IO:0x7fd6c986ab58>.puts() (Mocha::ExpectationError)

unsatisfied expectations:
  - expected exactly once, not yet invoked: #<IO:0x7fd6c986ab58>.puts('1.0.0')
from rbenv/versions/2.1.1/lib/ruby/gems/2.1.0/gems/test-unit-2.5.5/lib/test/unit/ui/console/testrunner.rb:389:in `nl'

代码:

def version
  say VERSION
end 

测试:

def test_should_print_version
  $stdout.expects(:puts).with(VERSION)
  App::CLI.start %W(version)
end 

有趣的是,$stdout.expects(:print).with(VERSION + "\n") 可以正常工作。我正在使用ruby 2.1.1p76

似乎第一个异常是由于 puts 被调用而第二个异常是由于它没有被调用。我应该以不同的方式使用expect 吗?

【问题讨论】:

    标签: ruby gem thor


    【解决方案1】:

    我按照here的建议将 $stdout 重定向到 StringIO 的实例来解决这个问题

    require 'stringio'
    
    module Kernel
      def capture_stdout
        out = StringIO.new
        $stdout = out
        yield
        return out
      ensure
        $stdout = STDOUT
      end
    end
    

    更新测试:

    def test_should_print_version
      #$stdout.expects(:puts).with(VERSION)
      out = capture_stdout { App::CLI.start %W(version) }
      assert_match VERSION, out.string
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多