Skip to content

Instantly share code, notes, and snippets.

@sambostock
Last active March 16, 2022 19:38
Show Gist options
  • Save sambostock/e70723890d7831a3e6cf89f84f330e5f to your computer and use it in GitHub Desktop.
Save sambostock/e70723890d7831a3e6cf89f84f330e5f to your computer and use it in GitHub Desktop.
Naively forbidding inheritance from classes defining tests
require 'minitest/autorun'
module ForbidSubclassingIfTestMethodsDefined
DuplicateTestsError = Class.new(StandardError)
def inherited(klass)
unless runnable_methods.empty?
raise DuplicateTestsError, "Do not inherit from #{self}, as the tests it defines would be duplicated in #{klass}"
end
super
end
end
Minitest::Test.extend(ForbidSubclassingIfTestMethodsDefined)
class Grandparent < Minitest::Test
# no tests
end
class Parent < Grandparent # okay
def test_example
end
end
class Child < Parent # boom
end
# minitest_parent.rb:7:in `inherited':
# Do not inherit from Parent, as the tests it defines would be duplicated in Child
# (ForbidSubclassingIfTestMethodsDefined::DuplicateTestsError)
# from minitest_parent.rb:25:in `<main>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment