Skip to content

Instantly share code, notes, and snippets.

@yevgenko
Last active September 30, 2022 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yevgenko/ba31a26f3f94961446d42ca504007582 to your computer and use it in GitHub Desktop.
Save yevgenko/ba31a26f3f94961446d42ca504007582 to your computer and use it in GitHub Desktop.
Freezing random generator and capturing output of ruby script without changing original file ['jbrains/trivia', 'golden master']
require 'stringio'
def capture_stdout_string
io = StringIO.new
capture_stdout(io) do
yield
end
io.string
end
def capture_stdout(io)
original_stdout = $stdout
$stdout = io
yield
ensure
$stdout = original_stdout
end
puts 'Testing namespace protection'
puts
puts "load 'test-load.rb', true"
result = capture_stdout_string do
load 'test-load.rb', true
puts @foo
end
puts "@foo = #{result}"
puts "load 'test-load.rb', false"
result = capture_stdout_string do
load 'test-load.rb', false
puts @foo
end
puts "@foo = #{result}"
puts
puts 'Testing the freezing of random number generator'
puts
puts 'First Sequence:'
srand(7777)
result = capture_stdout_string do
load 'script.rb', true
end
puts "Result: #{result}"
result = capture_stdout_string do
load 'script.rb'
end
puts "Result: #{result}"
puts
puts 'Second Sequence'
##
# Reset sequence of random numbers
# To match results of first and second runs
#
# Each call to 'rand' would generate new number
# but the sequence is repeatable, see test-srand.rb
srand(7777)
result = capture_stdout_string do
load 'script.rb'
end
puts "Result: #{result}"
result = capture_stdout_string do
load 'script.rb'
end
puts "Result: #{result}"
#!/usr/bin/env ruby
puts rand
srand 7777
puts rand
puts rand
puts rand
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment