Search code examples
ruby-on-railsrubyexceptiontestingtestcase

How to test whether any exception was rescued?


Is there a way to find out whether any exception was raised and rescued during the execution of some code?

Preferably in tests written with ActiveSupport::TestCase and not RSpec

Is there any global ruby exception stack or something, which I could check?


Solution

  • As clarified in the comments, OP needed it for debug purposes as opposed to write tests with it.


    Kernel#set_trace_func lets you intercept low level events such as an error being raised:

    set_trace_func(proc do |event, *_|
      puts 'Raised!' if event == 'raise'
    end)
    
    raise 'Oh, no!' rescue :foo
    

    You can run #set_trace_func before the code you were trying to debug. If no exception was raised, but a raise was registered by the hook - someone rescued it.


    This can create some noise depending on what you are executing. Fortunately, you can filter it down by file and line:

    set_trace_func(proc do |event, file, line, *_|
      if event == 'raise' && file == 'test.rb' && line == 42
        puts "Raised on #{file}:#{line}!"
      end
    end)
    

    It even gives you the binding, so you can drop down a debugger:

    require 'irb'
    
    set_trace_func(proc do |event, *_, error_binding, _|
      error_binding.irb if event == 'raise'
    end)
    
    def foo
      bar = 42
      raise 'Oh, no!' rescue :baz
    end
    
    foo
    
    # Opens an irb
    # > bar # => 42