Guest User

Untitled

a guest
Feb 18th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. class CaptureOutput
  2.  
  3. # Use in test examples to run a command *once*, and then
  4. # have the stdout and/or stderr available for testing
  5. #
  6. # out = CaptureOutput.run do
  7. # run_some_command
  8. # end
  9. #
  10. # expect(out.stdout).to match(/some output/)
  11. # expect(out.stderr).to match(/some texts/)
  12. #
  13. # All of the output is recorded into files: "log/spec/output_NNNN_NAME.txt",
  14. # where NAME is either 'out' or 'err', and 'NNNNN' is the current process id.
  15.  
  16. def self.run
  17. new.run { yield }
  18. end
  19.  
  20. def initialize
  21. @orig_stdout, @orig_stderr = $stdout, $stderr
  22. reset
  23. end
  24.  
  25. def reset
  26. @stdout, @stderr = StringIO.new, StringIO.new
  27. end
  28.  
  29. def run
  30. $orig_stdout, $orig_stderr = $stdout, $stderr
  31. $stdout, $stderr = @stdout, @stderr
  32. begin
  33. yield
  34. ensure
  35. $stdout, $stderr = @orig_stdout, @orig_stderr
  36. record_all_output
  37. end
  38. self
  39. end
  40.  
  41. def stdout
  42. @stdout.string
  43. end
  44.  
  45. def stderr
  46. @stderr.string
  47. end
  48.  
  49. private
  50.  
  51. def record_all_output
  52. record_output('out', stdout)
  53. record_output('err', stderr)
  54. end
  55.  
  56. def record_output(name, text)
  57. File.open(io_file_name(name), 'a+') {|file| file.write text}
  58. end
  59.  
  60. def io_file_name(name)
  61. File.join(spec_log_dir, "output_#{$PID}_#{name}.txt")
  62. end
  63.  
  64. def spec_log_dir
  65. File.join(Rails.root, 'log/spec').tap do |dir|
  66. Dir.exist?(dir) || FileUtils.mkdir_p(dir)
  67. end
  68. end
  69. end
Add Comment
Please, Sign In to add comment