Pretty-print arrays on failure

℡╲_俬逩灬. 提交于 2021-01-27 08:21:29

问题


describe Rspec do
  it 'should print arrays in a readable manner' do
    arr = [
      [0, :a, -1],
      [1, :b, -2],
      [2, :c, -3],
      [3, :d, -4],
      [4, :e, -5], 
      [6, :g, -7], 
      [7, :h, -8], 
      [8, :i, -9]
    ]
    arr.should eql []
  end
end

On failure:

Failures:

1) Rspec should print arrays in a readable manner
   Failure/Error: arr.should eql []

     expected: []
          got: [[0, :a, -1], [1, :b, -2], [2, :c, -3], [3, :d, -4], [4, :e, -5], [6, :g, -7], [7, :h, -8], [8, :i, -9]]

Is there a way to tell Rspec to pretty print its failures? My real-world example can have anywhere from 10 - 40 elements in the array, with each element being an array of 5 ints and a string.


回答1:


Although this is not a generic solution for handling display of all objects in all failure messages, you can customize a failure message for any one example, using the technique described in https://www.relishapp.com/rspec/rspec-expectations/docs/customized-message.

Combined with a customization of Ruby's standard prettyprint function to use a smaller line width and return its result as a string, gives you:

arr.should be_empty, "expected: empty array\ngot:\n#{PP.pp(arr,'',20)}"


来源:https://stackoverflow.com/questions/19660735/pretty-print-arrays-on-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!