Skip to content

Instantly share code, notes, and snippets.

@emerose
Created August 5, 2010 04:08
Show Gist options
  • Save emerose/509215 to your computer and use it in GitHub Desktop.
Save emerose/509215 to your computer and use it in GitHub Desktop.
require 'open3'
class RunningMan
def initialize(*cmd)
@cmd = cmd
end
attr_reader :status, :output, :error
def run
input, output, err = Open3.popen3(*@cmd)
input.close
@output = output.read
@error = err.read
@status = $?
output.close
err.close
success?
end
def exit_status
status.try(:exitstatus)
end
def success?
status.try(:success?)
end
end
equire 'spec_helper'
describe RunningMan do
describe "initialize" do
it "takes a command string or a command and list of arguments as its parameter" do
RunningMan.new("which")
RunningMan.new("which", "ls")
end
end
describe "#run" do
subject { RunningMan.new("echo hi") }
it "executes the command" do
subject.run
end
it "returns the process exit status as true on success" do
subject.stub(:success?).and_return(true)
subject.run.should be_true
end
it "returns the process exit status as false on failure" do
subject.stub(:success?).and_return(false)
subject.run.should be_false
end
end
describe "#exit_status" do
before do
@in, @out, @err = StringIO.new, StringIO.new, StringIO.new
Open3.stub(:popen3).and_return([@in, @out, @err])
Process.stub(:wait)
end
subject { RunningMan.new("asdf") }
it "returns the numerical value of the process status" do
$?.stub(:exitstatus).and_return(1)
subject.run
subject.exit_status.should == 1
end
end
describe "input/output" do
before do
@in, @out, @err = StringIO.new, StringIO.new, StringIO.new
Open3.stub(:popen3).and_return([@in, @out, @err])
Process.stub(:wait)
end
subject { RunningMan.new("asdf") }
it "records the process' STDOUT and makes it accessible" do
@out << "standard output"
@out.rewind
subject.run
subject.output.should == "standard output"
end
it "records the process' STDERR and makes it accessible" do
@err << "standard error"
@err.rewind
subject.run
subject.error.should == "standard error"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment