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

2

「response」の代わりに「*response」を入れる必要があったと思います。

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

これにより、配列である 1 つの引数ではなく、4 つの文字列引数が and_yield ("arity of 4") に送信されます。

于 2015-07-07T15:54:21.667 に答える