rspec - 如何向发生故障/错误的地方添加更多信息

Mic*_*ant 4 ruby rspec

如果测试失败,我想输出一堆信息。

然而,当我输出信息时,它出现在 rspec 输出部分之前Failures:,而不是特定规范失败信息所在的位置(行号等)

rspec 中是否有一种方法可以让规范在故障本身中显示信息而不是单独显示信息?

我以为我是一个绕钩子,但是......

警告:周围钩子不会像钩子之前和之后那样与示例共享状态。这意味着您不能在周围的钩子和示例之间共享实例变量。```

Mik*_* K. 6

您可以在测试中使用 lambda:

  expect(page).to have_text("Doesn't exist"), lambda { "This failed for all sorts of reasons, let me list them out here: #{detailed info}." }
Run Code Online (Sandbox Code Playgroud)

会给你这样的输出:

    Failures:
  1) Blah blah blah
     Failure/Error: expect(page).to have_text("Doesn't exist"), lambda { "This failed for all sorts of reasons, let me list them out here: nil." }
       This failed for all sorts of reasons, let me list them.
     # ./spec/features/search_results_spec.rb:19:in `block (2 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)

expect(x).to eq y.count如果您的代码类似于仅附加 lambda 给出的 2 个参数,但预期为 0..1,那么这可能会有点棘手。为了解决这个问题,请使用如下格式

expect(x).to (eq y.count), lambda { "message" }
Run Code Online (Sandbox Code Playgroud)