contest.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. require "test/unit"
  2. # Test::Unit loads a default test if the suite is empty, whose purpose is to
  3. # fail. Since having empty contexts is a common practice, we decided to
  4. # overwrite TestSuite#empty? in order to allow them. Having a failure when no
  5. # tests have been defined seems counter-intuitive.
  6. class Test::Unit::TestSuite
  7. def empty?
  8. false
  9. end
  10. end
  11. # Contest adds +teardown+, +test+ and +context+ as class methods, and the
  12. # instance methods +setup+ and +teardown+ now iterate on the corresponding
  13. # blocks. Note that all setup and teardown blocks must be defined with the
  14. # block syntax. Adding setup or teardown instance methods defeats the purpose
  15. # of this library.
  16. class Test::Unit::TestCase
  17. def self.setup(&block)
  18. define_method :setup do
  19. super(&block)
  20. instance_eval(&block)
  21. end
  22. end
  23. def self.teardown(&block)
  24. define_method :teardown do
  25. instance_eval(&block)
  26. super(&block)
  27. end
  28. end
  29. def self.context(name, &block)
  30. subclass = Class.new(self)
  31. remove_tests(subclass)
  32. subclass.class_eval(&block) if block_given?
  33. const_set(context_name(name), subclass)
  34. end
  35. def self.test(name, &block)
  36. define_method(test_name(name), &block)
  37. end
  38. class << self
  39. alias_method :should, :test
  40. alias_method :describe, :context
  41. end
  42. private
  43. def self.context_name(name)
  44. "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}".to_sym
  45. end
  46. def self.test_name(name)
  47. "test_#{sanitize_name(name).gsub(/\s+/,'_')}".to_sym
  48. end
  49. def self.sanitize_name(name)
  50. name.gsub(/\W+/, ' ').strip
  51. end
  52. def self.remove_tests(subclass)
  53. subclass.public_instance_methods.grep(/^test_/).each do |meth|
  54. subclass.send(:undef_method, meth.to_sym)
  55. end
  56. end
  57. end