0

At the moment, this code just runs my entire program and I'm not sure why. I've included:

 if __FILE__ == $0
     game = Game.new("Harry", "Nick")
 end  

In my script but it still starts running the entire program. My goal is to print out the players' names using an instance method called #players. The closest I've come so far is with using let(:game), but all it did was fails the test saying it printed :game instead of the names of the players. Now I can't even get it to fail because it is just running the script.

require "tictactoe"

describe Game do
   describe "#players" do
       let(:game) do
            new_game = Game.new("Harry", "Nick")
            new_game.players
        end

       it "displays player names" do
            expect(game).to eq("Player 1: #{@player1}\nPlayer 2: #{@player2}")
       end
    end
end

The Game class that runs is included here:

 class Game

   def initialize(player1, player2)
      @player1 = player1
      @player2 = player2
      @rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

      @wins = [1, 2, 3], [4, 5, 6], [7, 8, 9], 
        [1, 4, 7], [2, 5, 8], [3, 6, 9],
        [1, 5, 9], [3, 5, 7]

      @selected_numbers = []
      @counter = 0

   game_board
   start_player1
 end

   def players
      puts "Player 1: #{@player1}"
      puts "Player 2: #{@player2}"
   end

   def game_board
      @rows.each do |r|
      puts r.each { |c| c }.join(" ")
   end
   end

   def start_player1
      puts "#{@player1}: Please enter a number for your X to go"
      player1_input = STDIN.gets.chomp


      locate_player1_input(player1_input)
  end
Harry B.
  • 411
  • 1
  • 4
  • 21

1 Answers1

0

Remove calls to all functions:

game_board
start_player1

from your constructor. What you are doing currently is actually:

  1. Instantiate Game;
  2. Call game_board (which in turn prints out the board);
  3. Call start_player1, which, surprisingly, starts player1’s moves.

But this won’t fix your test. In test you compare the string to the result of call to puts. Make methods return values, not print them, or use to_stdout rspec matcher.

Community
  • 1
  • 1
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • Thanks! I got it to work. I don't understand how I can remove those methods from the constructor and still have my program work. Like, if I get the tests to pass, the program won't work, and vice versa. Is there a way to combat this? – Harry B. Jul 13 '16 at 05:08
  • You should continue calling methods on created `Game` instance, like `game = Game.new`, `game.board` afterwards to show a board. `game.start_player1` to start a game itself etc. It’s a normal control flow, that should be implemented: `if __FILE__ == $0 ; game = Game.new("Harry", "Nick") ; game.board ; game.start_player1 ; ... ; end` – Aleksei Matiushkin Jul 13 '16 at 05:41