Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class CaptureOutput
- # Use in test examples to run a command *once*, and then
- # have the stdout and/or stderr available for testing
- #
- # out = CaptureOutput.run do
- # run_some_command
- # end
- #
- # expect(out.stdout).to match(/some output/)
- # expect(out.stderr).to match(/some texts/)
- #
- # All of the output is recorded into files: "log/spec/output_NNNN_NAME.txt",
- # where NAME is either 'out' or 'err', and 'NNNNN' is the current process id.
- def self.run
- new.run { yield }
- end
- def initialize
- @orig_stdout, @orig_stderr = $stdout, $stderr
- reset
- end
- def reset
- @stdout, @stderr = StringIO.new, StringIO.new
- end
- def run
- $orig_stdout, $orig_stderr = $stdout, $stderr
- $stdout, $stderr = @stdout, @stderr
- begin
- yield
- ensure
- $stdout, $stderr = @orig_stdout, @orig_stderr
- record_all_output
- end
- self
- end
- def stdout
- @stdout.string
- end
- def stderr
- @stderr.string
- end
- private
- def record_all_output
- record_output('out', stdout)
- record_output('err', stderr)
- end
- def record_output(name, text)
- File.open(io_file_name(name), 'a+') {|file| file.write text}
- end
- def io_file_name(name)
- File.join(spec_log_dir, "output_#{$PID}_#{name}.txt")
- end
- def spec_log_dir
- File.join(Rails.root, 'log/spec').tap do |dir|
- Dir.exist?(dir) || FileUtils.mkdir_p(dir)
- end
- end
- end
Add Comment
Please, Sign In to add comment