我正在使用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“代码,我只剩下一个空的数据结构。
我想知道我怎样才能正确地做到这一点?
谢谢!
发布于 2018-05-03 18:17:16
为了给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发布于 2015-07-07 23:54:22
我认为你需要写"*response“而不是”response“。
allow(Open3).to receive(:popen3).with(command).and_yield(*response)这将发送4个字符串参数到and_yield (“4的数量”),而不是一个参数,这是一个数组。
https://stackoverflow.com/questions/26049302
复制相似问题