Ruby:尝试测试STDERR输出时RSpec失败

问题描述 投票:0回答:1

我有collector.rb文件,内容如下:

class Collector
  def initialize(input)
    raise ArgumentError, 'must be positive integer' unless input.to_i.positive?
  end
  # more code...
end

begin
  Collector.new(*ARGV).do_something
rescue ArgumentError => e
  warn e.message
end

因此,当我在终端中执行$ ruby collector.rb时,我会按预期获得wrong number of arguments (given 0, expected 1) from Ruby docs

在我的测试文件中,我有:

require 'rspec'
require './collector'

RSpec.describe Collector do
  let(:exec) { File.expand_path('../collector.rb', File.dirname(__FILE__)) }

  describe 'input in console' do
    context 'when wrong number of arguments' do
      specify { expect {`ruby #{exec} `}.to output('wrong number of arguments (given 0, expected 1)').to_stderr }
    end
  end
end

此刻我的测试失败了,尽管我遵循建议STDERR,但它无法检测到from here的任何输出请问我在这里做错了什么?我很高兴收到有关如何修复我的代码的任何提示。

ruby error-handling rspec stderr argv
1个回答
0
投票

Ruby中的反引号在单独的进程中运行命令。当测试to_output...to_stderr时,将在父进程(RSpec)而非子进程(ruby)上对其进行测试。

为了测试子进程stderr,可以使用Open3.popen3来访问进程stderr。

尝试做某事(未测试):

Open3.popen3
© www.soinside.com 2019 - 2024. All rights reserved.