Skip to content

Instantly share code, notes, and snippets.

@myronmarston
Created January 15, 2014 19:06
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 myronmarston/8442297 to your computer and use it in GitHub Desktop.
Save myronmarston/8442297 to your computer and use it in GitHub Desktop.
in_sub_process for test isolation
module InSubProcess
if Process.respond_to?(:fork) && !(RUBY_PLATFORM == 'java' && RUBY_VERSION == '1.8.7')
# Useful as a way to isolate a global change to a subprocess.
def in_sub_process
readme, writeme = IO.pipe
pid = Process.fork do
exception = nil
begin
yield
rescue Exception => e
exception = e
end
writeme.write Marshal.dump(exception)
readme.close
writeme.close
exit! # prevent at_exit hooks from running (e.g. minitest)
end
writeme.close
Process.waitpid(pid)
exception = Marshal.load(readme.read)
readme.close
raise exception if exception
end
else
def in_sub_process
pending "This spec requires forking to work properly, " +
"and your platform does not support forking"
end
end
end
describe MyClass do
include InSubProcess
it "does something in a subprocess" do
in_sub_process do
# spec code goes here
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment