【问题标题】:Using let and expect in rspec在 rspec 中使用 let 和 expect
【发布时间】:2016-07-13 04:49:30
【问题描述】:

目前,这段代码只是运行我的整个程序,我不知道为什么。我已经包括:

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

在我的脚本中,但它仍然开始运行整个程序。我的目标是使用名为#players 的实例方法打印出玩家的姓名。到目前为止,我最接近的是使用 let(:game),但它所做的只是没有通过测试,说它打印的是 :game 而不是玩家的名字。现在我什至不能让它失败,因为它只是在运行脚本。

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

运行的 Game 类包含在此处:

 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

【问题讨论】:

  • 由于我们不是算命先生,实际运行的代码可能会帮助我们了解发生了什么。请发帖tictactoe.rb

标签: ruby-on-rails ruby rspec


【解决方案1】:

删除对所有函数的调用:

game_board
start_player1

来自您的构造函数。你目前正在做的实际上是:

  1. 实例化Game;
  2. 致电game_board(反过来打印出白板);
  3. 调用start_player1,令人惊讶的是,它会启动 player1 的动作。

但这不会修复您的测试。在测试中,您将字符串与调用puts 的结果进行比较。使方法返回值,而不是打印它们,或者使用to_stdoutrspec匹配器。

【讨论】:

  • 谢谢!我让它工作了。我不明白如何从构造函数中删除这些方法并且仍然让我的程序工作。就像,如果我让测试通过,程序将无法运行,反之亦然。有没有办法解决这个问题?
  • 您应该继续在创建的Game 实例上调用方法,例如game = Game.newgame.board 之后显示板。 game.start_player1 启动游戏等。这是一个正常的控制流程,应该实现:if __FILE__ == $0 ; game = Game.new("Harry", "Nick") ; game.board ; game.start_player1 ; ... ; end
猜你喜欢
  • 2012-08-28
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多