2

我正在使用 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”代码,我只剩下一个空数据结构。

我想知道我怎样才能正确地做到这一点?

谢谢!

4

2 回答 2

3

要为 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
于 2018-05-03T10:17:15.507 回答
2

我认为您需要输入“*response”而不是“response”。

allow(Open3).to receive(:popen3).with(command).and_yield(*response)

这会将 4 个字符串 args 发送到 and_yield(“arity of 4”),而不是一个数组 arg。

于 2015-07-07T15:54:21.667 回答