This post originated from an RSS feed registered with Ruby Buzz
by Jim Weirich.
Original Post: Ruby Module Spotlight: Session
Feed Title: { | one, step, back | }
Feed URL: http://onestepback.org/index.cgi/synopsis.rss
Feed Description: Jim Weirich's Blog on Software Development, Ruby, and whatever else sparks his interest.
Here’s a sweet little module from Ara T. Howard. It is called
Session and will run a shell session under the control of a Ruby
script. Standard output and standard error are captured by the session
object and made available to the script.
How about a quick example …
bash = Session::Bash.new
stdout, stderr = bash.execute "ls"
p stdout # prints "trysession.rb\n"
The shell session created is persistent. Executing multiple commands in the
session is like typing multiple lines into a real shell, the state is
remembered from one command to the next. If you change the current
directory, subsequent commands will execute in the new location.
Environment variables set in the session will be remembered in later
commands.
bash = Session::Bash.new
bash.execute "export GREETING=hi"
out, err = bash.execute "echo $GREETING"
p out # print "hi\n"
If you pass an IO object to the session, it will append its output to that
object.
out = StringIO.new
bash = Session::Bash.new
bash.execute "ls", :stdout=>out
bash.execute "ls ..", :stdout=>out
p out # prints the output from both "ls" commands.
One possible use of Session is to test command line scripts where
you wish to check both standard output and standard error independently.
class TestVersion < Test::Unit::TestCase
def test_install
out = StringIO.new
bash = Session::Bash.new
bash.execute "export GEMPATH=#{TESTDIR}"
out, err = bash.execute "bin/gem --install testgem"
assert_equals 0, bash.exit_status
assert_equals "", err
assert_equals EXPECTED_OUTPUT, out
assert_test_gem_installed
end
end