Harry B. Harry B. - 4 months ago 21
Ruby Question

Using let and expect in rspec

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

Answer

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.

Comments