Start ruby debugger if rspec test fails

前端 未结 6 1789
谎友^
谎友^ 2021-02-05 05:11

Often, when a test fails, I spend quite sometime trying to figure out the what caused it to fail. It\'d be useful if RSpec could kick off a Ruby debugger when the test fails, so

6条回答
  •  醉梦人生
    2021-02-05 05:27

    You need to catch the ExpectationNotMatched exception while it's being constructed. Include the following code in your helpers somewhere and RSpec will stop when the exception is being constructed. This will be several levels deep inside the matchers, so in the debugger, say "where" then "up 5"or "up 6" and you'll be inside the instance_exec of your block. The debugger doesn't show the code correctly in the version I'm using, but you can "up" one more time and get to code running in the same context where your test is evaluated, so you can inspect the instance variables (but not local variables, it seems).

    require 'debugger'
    require 'rspec'
    
    Debugger.start
    class RSpec::Expectations::ExpectationNotMetError
      alias_method :firstaid_initialize, :initialize
    
      def initialize *args, &b
        send(:firstaid_initialize, *args, &b)
        puts "Stopped due to #{self.class}: #{message} at "+caller*"\n\t"
        debugger
        true # Exception thrown
      end
    end
    
    describe "RSpec" do
      it "should load use exceptions on should failure" do
        @foo = :bar    # An instance variable I can examine
        1.should == 2
      end
    end
    

提交回复
热议问题