Created
January 15, 2014 19:06
-
-
Save myronmarston/8442297 to your computer and use it in GitHub Desktop.
in_sub_process for test isolation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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