如果rspec测试失败,请启动ruby调试器

通常,当测试失败时,我花了很长时间试图找出导致测试失败的原因。 如果RSpec在测试失败时启动Ruby调试器会很有用,这样我就可以立即检查局部变量以深入了解原因。

我正在使用的解决方案现在看起来像这样:

# withing some test debugger unless some_variable.nil? expect(some_variable).to be_nil 

但是,这种方法很麻烦,因为我首先等待测试失败,然后添加调试器行,修复问题然后必须删除调试器行,而我希望它的工作更像gdb ,它有能力启动当遇到exception时,无需使用debugger语句来编写代码库。

编辑:我试过普利茅斯。 它对我来说不够可靠。 此外,开发历史似乎表明它不是一个非常受支持的gem,所以我宁愿不依赖它。

更新 :我尝试了pry-rescue并发现它很整洁。 但是,我经常使用宙斯,并且想知道是否有办法让它与pry-rescue

使用撬救 ,它是普利茅斯的精神inheritance者:

从自述文件:

如果您正在使用RSpec或respec,则可以使用rescue rspec或rescue respec在每次测试失败时打开一个pry会话:

 $ rescue rspec From: /home/conrad/0/ruby/pry-rescue/examples/example_spec.rb @ line 9 : 6: 7: describe "Float" do 8: it "should be able to add" do => 9: (0.1 + 0.2).should == 0.3 10: end 11: end RSpec::Expectations::ExpectationNotMetError: expected: 0.3 got: 0.30000000000000004 (using ==) [1] pry(main)> 

如果没有debugger在块的范围内,你将无法轻松访问局部变量,但是RSpec为你提供了大概的钩子,你可以这样做:

 config.around(:each) do |example| result = example.run debugger if result.is_a?(Exception) puts "Debugging enabled" end 

然后,您可以访问@ivarssubject / let(:var)内容。

我喜欢@ jon-rowe的解决方案(不需要额外的gem),只需稍加编辑:我真的不关心其他错误,就像RSpec::Expectations::ExpectationNotMetError

  config.around(:each) do |example| example.run.tap do |result| debugger if result.is_a?(RSpec::Expectations::ExpectationNotMetError) end end 

您需要在构造ExpectationNotMatchedexception时捕获它。 在某个地方的助手中包含以下代码,RSpec将在构造exception时停止。 这将是匹配器内部的几个级别,因此在调试器中,说“where”然后“up 5”或“up 6”并且您将位于块的instance_exec中。 调试器没有在我正在使用的版本中正确显示代码,但是您可以再次“启动”并获得在评估测试的同一上下文中运行的代码,这样您就可以检查实例变量(但是似乎不是局部变量)。

 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 

您可以使用plymouth gem https://github.com/banister/plymouth 。 它使用的是 ,是(更好的) irb的替代品。

HTH

你可以试试hammertime 。 每当引发exception时,它将停止并提示您进入交互式调试会话。