Ruby: RSpec 尝试测试 STDERR 输出时失败
Ruby: RSpec fails when try to test STDERR output
我有 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。
像这样尝试(未测试):
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
我有 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。
像这样尝试(未测试):
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