1

I know I am missing something simple here. I want to write a test that checks if an array of array has been outputted. The test keeps failing but what the test expects is the same that the method is giving.

connect4.rb

class Board
  attr_accessor :board
  def make_and_print_board
    grid = Array.new(6) { Array.new(6)}
    p grid
  end
end

connect4_spec.rb

require  './lib/connect4'


RSpec.describe Board do
  let (:new_board) {Board.new}
  it "prints board" do
    expect{new_board.make_and_print_board}.to output(
      Array.new(6) { Array.new(6)}
    ).to_stdout
  end
end


This is the error...

 1) Board prints board
     Failure/Error:
           expect{new_board.make_and_print_board}.to output(
             Array.new(6) { Array.new(6)}

           ).to_stdout

       expected block to output [[nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil]] to stdout, but output "[nil, nil, nil, nil, nil, nil]\n[nil, nil, nil, nil, nil, nil]\n[nil, nil, nil, nil, nil, nil]\n[nil, nil, nil, nil, nil, nil]\n[nil, nil, nil, nil, nil, nil]\n[nil, nil, nil, nil, nil, nil]\n"

What am I missing here? Why isn't it passing? How can I get this test to pass?

1
  • 3
    you're outputting a string representation of an array of array's and then telling RSpec you expect it to output an. array of array's...need to tell RSpec to expect a string (or regex to match a string against) Commented Jan 26, 2020 at 23:16

1 Answer 1

1

The correct way to write this test is to be verbose about your expectation. Test the exact value of what you expect ii to give. p will output a new line so write this way.

RSpec.describe Board do
  let (:new_board) {Board.new}
  it 'prints board' do
    p_output = "[[nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil]]\n"

    expect{new_board.make_and_print_board}.to output(p_output).to_stdout
  end
end

But you might want to add this spec if you care more about the internals:

  it 'it outputs a 6 x 6 2d array' do
    expect( new_board.make_and_print_board ).to match_array Array.new(6) { Array.new(6)} 
  end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.