Vig*_*esh 19 rspec ruby-on-rails ruby-debug pry
通常,当测试失败时,我花了很长时间试图找出导致测试失败的原因.如果RSpec在测试失败时启动Ruby调试器会很有用,这样我就可以立即检查局部变量以深入了解原因.
我正在使用的解决方案现在看起来像这样:
# withing some test
debugger unless some_variable.nil?
expect(some_variable).to be_nil
Run Code Online (Sandbox Code Playgroud)
但是,这种方法很麻烦,因为我首先等待测试失败,然后添加调试器行,修复问题然后必须删除调试器行,而我希望它的工作更像是gdb
哪个有能力启动时如果遇到异常,则无需使用debugger
语句来编写代码库.
编辑:我试过普利茅斯.它对我来说还不够可靠.此外,开发历史似乎表明它不是一个非常受支持的宝石,所以我宁愿不依赖它.
更新:我试过去pry-rescue
发现它很整洁.但是,我经常使用宙斯,并且想知道是否有办法让它适用pry-rescue
.
hor*_*guy 26
使用撬救,它是普利茅斯的精神继承者:
从自述文件:
如果您正在使用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)>
Run Code Online (Sandbox Code Playgroud)
小智 8
如果没有debugger
在块的范围内,您将无法轻松访问局部变量,但是RSpec
为您提供了周围的钩子,您可以这样做:
config.around(:each) do |example|
result = example.run
debugger if result.is_a?(Exception)
puts "Debugging enabled"
end
Run Code Online (Sandbox Code Playgroud)
然后,您可以访问@ivars
和subject
/ let(:var)
content.
我喜欢@jon-rowe 的解决方案(不需要额外的宝石),稍作修改:我真的不像RSpec::Expectations::ExpectationNotMetError
.
config.around(:each) do |example|
example.run.tap do |result|
debugger if result.is_a?(RSpec::Expectations::ExpectationNotMetError)
end
end
Run Code Online (Sandbox Code Playgroud)
小智 5
来自 Rspec 文档:
RSpec 尝试提供有用的失败消息,但对于需要更具体信息的情况,您可以在示例中定义自己的消息。这适用于除运算符匹配器之外的任何匹配器。
我所做的就是在该消息中调用 pry。参见示例:
describe "failing" do
context "test" do
it "should start pry" do
a = 3
b = 1
expect(a).to be == b, "#{require 'pry';binding.pry}"
end
end
end
Run Code Online (Sandbox Code Playgroud)
调试愉快!