1
votes

I am new to Rspec and I want to create a rspec example for a method which prints a 2d array.

Method which prints the array:

 def print_array
    array.each do |row|
      row.each do |cell|
        print cell 
      end
      puts
    end
 end

For example, the result from the above code could be:

 0 0 0
 0 0 0
 0 0 0

So I want to create an expectation(rspec) for the above method.

I tried to check the puts and print (STDOUT) but didn't work:

 it "prints the array" do
   ...
   expect(STDOUT).to receive(:puts).with("0 0 0 ...")
   obj.print_array
 end

Is there any way to test what exactly is printed out?

2

2 Answers

2
votes

RSpec has an output matcher specifically for this type of thing, so your example will become something like

def print_array(array)
  array.each do |row|
    row.each do |cell|
      print cell
    end
    puts
  end
end

RSpec.describe 'print_array' do
  it 'prints the array' do

    expect do
      print_array([
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
    ])
    end.to output("000\n000\n000\n").to_stdout
  end
end
1
votes

Please refer to the following link. output_to_stdout matcher

we can write like this :

expect { puts "1" }.to output("1\n").to_stdout

so, your rspec test

matrix_format_str = "0 0 0\n0 0 0\n0 0 0\n"
expect { print_array }.to output(matrix_format_str).to_stdout