Skip to content

Instantly share code, notes, and snippets.

@toch
Created July 12, 2016 14:40
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 toch/7a15d8f6fd53f6c611a62973fbfc75c2 to your computer and use it in GitHub Desktop.
Save toch/7a15d8f6fd53f6c611a62973fbfc75c2 to your computer and use it in GitHub Desktop.
Test how we can release resources or processes when an exception is raised during test
require "minitest/autorun"
def raise_an_exception
raise "Raised!"
end
module Minitest
module Ensure
def ensure_to_call_after(name)
old_test_method = instance_method("test_#{name}")
define_method "test_#{name}" do
begin
old_test_method.bind(self).()
rescue StandardError => e
puts "Gotcha! #{e}"
fail
end
end
end
end
end
class TestMinitestEnsure < Minitest::Test
extend Minitest::Ensure
def setup
puts "Setup!"
end
def teardown
puts "TearDown!"
end
def test_one
assert raise_an_exception
end
def test_two
assert raise_an_exception
end
ensure_to_call_after :one
end
$ ruby ensure_teardown.rb
Run options: --seed 40063
# Running:
Setup!
Gotcha! Raised!
TearDown!
ESetup!
TearDown!
E
Finished in 0.000863s, 2317.3897 runs/s, 0.0000 assertions/s.
1) Error:
TestMinitestEnsure#test_one:
RuntimeError: Raised!
ensure.rb:4:in `raise_an_exception'
ensure.rb:35:in `test_one'
ensure.rb:13:in `call'
ensure.rb:13:in `block in ensure_to_call_after'
2) Error:
TestMinitestEnsure#test_two:
RuntimeError: Raised!
ensure.rb:4:in `raise_an_exception'
ensure.rb:39:in `test_two'
2 runs, 0 assertions, 0 failures, 2 errors, 0 skips
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment