【问题标题】:Rspec - capture stderr output of linux processRspec - 捕获 linux 进程的 stderr 输出
【发布时间】:2017-11-24 05:14:37
【问题描述】:

我想测试我的 bash 脚本向 stderr 输出了什么消息。 我试试这个:

require 'rspec'

describe 'My behaviour' do

  it 'should do something' do
    expect { `echo "foo" 1>&2` }.to output.to_stderr
  end
end

但似乎输出到 stderr 不是在测试期间发生的。

【问题讨论】:

    标签: ruby rspec stderr


    【解决方案1】:

    RSpec 的 output.to_stderr 匹配器正在寻找写入 $stdout/$stderr 的内容——你的 shell 命令没有这样做,因为它作为一个单独的子进程运行。

    为了对此进行测试,您需要显式捕获 shell 代码的 stdoutstderr。您可以使用Open3 standard library 轻松构建自己的实现,或者例如使用rspec-bash gem

    require 'rspec'
    require 'rspec/bash'
    
    describe 'My behaviour' do
      include Rspec::Bash
    
      let(:stubbed_env) { create_stubbed_env }
    
      it 'should do something' do
        stdout, stderr, status = stubbed_env.execute(
          'echo "foo" 1>&2'
        )
        expect(stderr).to eq('foo')
      end
    end
    

    【讨论】:

      【解决方案2】:

      找到了一种不太精确但更容易阅读的方法:

      require 'rspec'
      
      describe 'My behaviour' do
      
        it 'should do something' do
          expect { system('echo "foo" 1>&2 ') }.to output.to_stderr_from_any_process
        end
      end
      

      AFAIU - 它无法检查确切的消息,但对我来说已经足够了

      【讨论】:

      • 您可以查看确切的消息:.to output('foo').to_std_error_from_any_process -- read the docs
      猜你喜欢
      • 2012-10-04
      • 1970-01-01
      • 2013-03-01
      • 2014-07-09
      • 1970-01-01
      • 2023-03-03
      • 2020-06-23
      • 2018-05-04
      • 1970-01-01
      相关资源
      最近更新 更多