Search code examples
rubyrspecminimax

How to use RSpec to test negamax?


I'm working on a Tic Tac Toe and I have a #negamax method that returns the best position to computer to move to, and a #winner method that returns 1 (computer wins) or -1 (user wins). How can I test #negamax so that I guarantee that its implementation is right and that user never wins?

I have a few test cases in places, to test that it returns the best position, and it does, but it does not cover all possible cases. Right now, this is what I have (besides the test cases for the best choice):

it 'never allows user to win' do
  until game_over?
    unless is_ai?
      pos = empty_positions.sample
      move(pos, user)
    else
      pos = negamax(0, 1, -100, 100)
      move(pos, computer)
    end
  end
  if game.won?
    expect(winner).to eq(1)
  else
    expect(winner).to be_nil
  end
end

It does not seem very effective to just 'hope' that the test will never fail. What would be a better way to accomplish it?


Solution

  • but it does not cover all possible cases.

    Don't worry, this is normal, it's nearly impossible to simulate all the ways an application will be used. Testing some things can lead to huge increases in results. Testing “everything” is a waste of time. That’s because “everything” doesn’t matter. Only certain things matter. The right things matter.