我有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中的反引号在单独的进程中运行命令。当测试to_output...to_stderr
时,将在父进程(RSpec)而非子进程(ruby)上对其进行测试。
为了测试子进程stderr,可以使用Open3.popen3
来访问进程stderr。
尝试做某事(未测试):
Open3.popen3