Created
February 5, 2018 23:29
-
-
Save aks/7b3cdae96d3d3063d25c4f9293d5e361 to your computer and use it in GitHub Desktop.
Spec helper class: CaptureOutput.run { block }
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
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment