Skip to content

Instantly share code, notes, and snippets.

@Loschcode
Last active December 8, 2021 13:05
Show Gist options
  • Save Loschcode/4e35e7972b41b47606410ecb4da9b285 to your computer and use it in GitHub Desktop.
Save Loschcode/4e35e7972b41b47606410ecb4da9b285 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "tempfile"
# catch various system process output
module Engines::Core::Infrastructure::Utils
class CaptureProcess
class << self
def error(&block)
capture($stderr, &block)
end
def error?(error, &block)
error(&block).tap do |capture|
return true if capture.include? error.to_s
end
false
end
private
def capture(output, &block)
output_copy = output.dup
Tempfile.open "#{output}-redirect" do |temporary_file|
output.reopen temporary_file.path, "w+"
yield if block
output.reopen output_copy
temporary_file.read
end
end
end
end
end
# frozen_string_literal: true
require "rails_helper"
RSpec.describe Engines::Core::Infrastructure::Utils::CaptureProcess do
describe ".error" do
subject { described_class.error { nil } }
it { expect { subject }.not_to raise_error }
context "with an error" do
it { expect(described_class.error { $stderr.puts("RandomError") }).to include("RandomError") }
it do
allow(described_class).to receive(:capture)
subject
expect(described_class).to have_received(:capture)
end
end
end
describe "error?" do
subject do
described_class.error? error do
command
end
end
let(:error) { "ValidError" }
let(:command) { nil }
it { expect(subject).to eq(false) }
context "with the targeted error" do
let(:command) { $stderr.puts("ValidError") }
it { expect(subject).to eq(true) }
end
context "with an error" do
let(:error) { "AnotherError" }
let(:command) { $stderr.puts("ValidError") }
it { expect(subject).to eq(false) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment