Skip to content

Instantly share code, notes, and snippets.

@herrphon
Last active April 20, 2023 04:07
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save herrphon/2d2ebbf23c86a10aa955 to your computer and use it in GitHub Desktop.
ruby rspec capture I/O stdout/stderr
require 'pp'
module Helper
def capture(&block)
begin
$stdout = StringIO.new
$stderr = StringIO.new
yield
result = {}
result[:stdout] = $stdout.string
result[:stderr] = $stderr.string
ensure
$stdout = STDOUT
$stderr = STDERR
end
result
end
end
RSpec.configure do |config|
config.include Helper
end
class MyDummy
def self.do_something
puts 'hello test'
$stderr.puts 'error error error'
end
end
describe MyDummy do
it "has the correct output" do
result = capture{ MyDummy.do_something }
puts "Result:"
pp result
puts "###"
expect(result[:stdout]).to include("hello")
end
end
@AlexWayfer
Copy link

RSpec stops (without fails) when sub-command returns status 1 (and stderr).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment