Last active
April 20, 2023 04:07
-
-
Save herrphon/2d2ebbf23c86a10aa955 to your computer and use it in GitHub Desktop.
ruby rspec capture I/O stdout/stderr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
RSpec stops (without fails) when sub-command returns status 1 (and
stderr
).