-->

启动Ruby调试如果rspec的测试失败(Start ruby debugger if rspec

2019-09-01 10:33发布

通常情况下,当一个测试失败了,我花了相当一段时间试图找出什么原因造成的失败。 这将会是有用的,如果在测试失败时的RSpec能揭开序幕一个Ruby调试器,这样我就可以立即检查局部变量来向下钻取的原因。

我现在使用的变通办法看起来是这样的:

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

但是,这种方法比较麻烦,因为我第一次等待测试失败,然后添加调试线,解决这个问题,然后不得不删除调试线,而我想它的工作更像是gdb其中有踢的能力当异常被击中,而无需对辣椒您的代码库与debugger语句。

编辑:我试过普利茅斯。 它没有可靠的工作对我来说足够。 另外,发展历史似乎表明,它不是一个很好的支持的宝石,所以我宁愿不依赖于它。

更新 :我尝试了pry-rescue ,并发现它是整齐的。 但是,我用宙斯了很多,不知道是否有一种方法,使其与工作pry-rescue

Answer 1:

使用撬救援 ,它的精神继承普利茅斯:

自述:

如果您使用的RSpec或respec,您可以使用RSpec的救援或救援respec打开,每次考试失败撬会话:

$ 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)>


Answer 2:

没有你将不能访问本地变量(容易) debugger在街区的保护范围,但RSpec为您提供周围让你这样做的钩子:

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

然后,您可以访问@ivarssubject / let(:var)的内容在这一点上。



Answer 3:

我喜欢@乔恩-罗公司的解决方案有轻微的编辑(无需额外的宝石):我真的不关心不亚于其他错误RSpec::Expectations::ExpectationNotMetError

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


Answer 4:

你需要赶上ExpectationNotMatched例外,它被建造时。 包括下面的代码在你的助手的地方,并正在建设中的异常时的RSpec将停止。 这将是好几层深的匹配器里面,所以在调试器,说:“在那里”,然后“高达5”或“升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


Answer 5:

您可以使用普利茅斯的宝石https://github.com/banister/plymouth了点。 它虽然采用 ,一个(更好)替代IRB。

HTH



Answer 6:

你可以试试hammertime 。 它将停止,并提示每当产生一个异常带你进入一个交互式调试会话。



文章来源: Start ruby debugger if rspec test fails