rescuable_test.rb 2.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
require 'abstract_unit'

class WraithAttack < StandardError
end

class NuclearExplosion < StandardError
end

class MadRonon < StandardError
end

12 13 14
class CoolError < StandardError
end

15 16 17 18 19
class Stargate
  attr_accessor :result

  include ActiveSupport::Rescuable

20 21
  rescue_from WraithAttack, :with => :sos_first

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
  rescue_from WraithAttack, :with => :sos

  rescue_from NuclearExplosion do
    @result = 'alldead'
  end
  
  rescue_from MadRonon do |e|
    @result = e.message
  end

  def dispatch(method)
    send(method)
  rescue Exception => e
    rescue_with_handler(e)
  end

  def attack
    raise WraithAttack
  end

  def nuke
    raise NuclearExplosion
  end

  def ronanize
    raise MadRonon.new("dex")
  end

  def sos
    @result = 'killed'
  end
53 54 55 56 57

  def sos_first
    @result = 'sos_first'
  end

58 59
end

60 61 62 63 64 65 66 67 68 69 70 71 72
class CoolStargate < Stargate
  attr_accessor :result

  include ActiveSupport::Rescuable

  rescue_from CoolError, :with => :sos_cool_error

  def sos_cool_error
    @result = 'sos_cool_error'
  end
end


73 74 75
class RescueableTest < Test::Unit::TestCase
  def setup
    @stargate = Stargate.new
76
    @cool_stargate = CoolStargate.new
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
  end

  def test_rescue_from_with_method
    @stargate.dispatch :attack
    assert_equal 'killed', @stargate.result
  end
  
  def test_rescue_from_with_block
    @stargate.dispatch :nuke
    assert_equal 'alldead', @stargate.result
  end
  
  def test_rescue_from_with_block_with_args
    @stargate.dispatch :ronanize
    assert_equal 'dex', @stargate.result
  end  
93 94 95 96 97 98 99

  def test_rescues_defined_later_are_added_at_end_of_the_rescue_handlers_array
    expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon"]
    result = @stargate.send(:rescue_handlers).collect {|e| e.first}
    assert_equal expected, result
  end

100 101 102 103 104 105
  def test_children_should_inherit_rescue_defintions_from_parents_and_child_rescue_should_be_appended
    expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon", "CoolError"]
    result = @cool_stargate.send(:rescue_handlers).collect {|e| e.first}
    assert_equal expected, result
  end

106
end