【问题标题】:Ruby: RSpec fails when try to test STDERR outputRuby:尝试测试 STDERR 输出时 RSpec 失败
【发布时间】:2020-03-16 01:29:33
【问题描述】:

我有类似这样的 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 collector.rb运行程序,ARGV将为空并且Collector::initialize被零参数调用。

标签: ruby error-handling rspec stderr argv


【解决方案1】:

ruby 中的反引号在单独的进程中运行命令。当您测试 to_output...to_stderr 时,您在父进程 (RSpec) 上测试它,而不是子进程 (ruby)。

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

试试这样(未测试):

require 'open3'

specify do
  Open3.popen3("ruby #{exec}") do |_stdin, _stdout, stderr|
    expect(stderr.read.strip).to eq('wrong number of arguments (given 0, expected 1)')
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    相关资源
    最近更新 更多