我正在使用rspec在Ruby中开发一些测试用例。
我试图模拟popen3函数。
然而,在保持阻塞形式的同时,我无法捕获预期的输出信息:
Class MyClass
def execute_command
Open3.popen3(command) do |stdin, stdout, stderr, wait_thr|
output['wait_thr'] = wait_thr.value
while line = stderr.gets
output['stderr'] += line
end
end
return output
end
end
为了模拟该功能,我正在做以下操作:
it 'should do something'
response = []
response << 'stdin'
response << 'stdout'
response << 'test'
response << 'exit 0'
# expect
allow(Open3).to receive(:popen3).with(command).and_yield(response)
# when
output = myClassInstance.execute_script
#then
expect(output['wait_thr'].to_s).to include('exit 0')
模拟函数不会输入"do"代码,我只剩下一个空的数据结构。
我在想我该怎么做?
谢谢!
为了给Chris Reisor的答案添加更多的上下文,这是对我有效的方法:
我有一段代码,如下所示。
Open3.popen2e(*cmd) do |_, stdout_and_stderr, wait_thr|
while (line = stdout_and_stderr.gets)
puts line
end
raise NonZeroExitCode, "Exited with exit code #{wait_thr.value.exitcode}" unless wait_thr.value.success?
end
我的测试设置如下所示。
let(:wait_thr) { double }
let(:wait_thr_value) { double }
let(:stdout_and_stderr) { double }
before do
allow(wait_thr).to receive(:value).and_return(wait_thr_value)
allow(wait_thr_value).to receive(:exitcode).and_return(0)
allow(wait_thr_value).to receive(:success?).and_return(true)
allow(stdout_and_stderr).to receive(:gets).and_return('output', nil)
allow(Open3).to receive(:popen2e).and_yield(nil, stdout_and_stderr, wait_thr)
end
我认为您需要放置"*response"而不是"response"
allow(Open3).to receive(:popen3).with(command).and_yield(*response)
这将向and_yield("arity of 4")发送4个字符串arg,而不是一个数组arg。