Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty-print arrays on failure

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.

like image 527
yurisich Avatar asked Nov 02 '22 11:11

yurisich


1 Answers

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)}"
like image 120
Peter Alfvin Avatar answered Nov 15 '22 06:11

Peter Alfvin