繁体   English   中英

NoMethodError:在gets.chomp上运行Ruby Rspec时nil:NilClass的未定义方法“chomp”

[英]NoMethodError: undefined method `chomp' for nil:NilClass while running Ruby Rspec on gets.chomp

这是我在此的头一篇博文。 我对 Ruby 相当陌生,尤其是 RSpec,并且一直遇到问题。 我编写了一个使用gets.chomp 接收玩家输入的方法。 但是我在另一种方法中调用了这个方法

def prompt_move
        loop do     
            @move = gets.chomp.to_i 
            return move if valid_move?(move)                    
            puts "Invalid input. Enter a column number between 1 and 7"
        end
    end

    def valid_move?(move)
        @move.is_a?(Integer) && @move.between?(1, 7)
    end

    def play_round
        print_board
        prompt_player
        @move = prompt_move     
    end     

这是我的 RSpec 测试的代码:

describe ConnectFour do
  subject(:game) { described_class.new }
    let(:player){ double(Player) }

describe '#prompt_move' do      
        context 'move is a valid input' do          
            before do
                allow(game).to receive(:gets).and_return('3\n')
            end
            
            it 'returns move and stops the loop' do
                error_message = 'Invalid input. Enter a column number between 1 and 7'
                expect(game).to_not receive(:puts).with(error_message)              
                game.prompt_move
            end
        end
            
        context 'when given one invalid input, then a valid input' do
            before do
                letter = 'a'
                valid_input = '1'
                allow(game).to receive(:gets).and_return(letter, valid_input)
            end

            it 'completes loop and displays error message once' do                          
                error_message = 'Invalid input. Enter a column number between 1 and 7'              
                expect(game).to receive(:puts).with(error_message).once             
                game.prompt_move
            end
        end
    end

如果我从 #play_round 中删除 #prompt_move 方法,则测试通过,没有任何问题。 但是,当我尝试从 #play_round 中调用它时,它给了我 NoMethodError: undefined method `chomp' for nil:NilClass

我一直在努力找出导致此错误的原因,因此我们将不胜感激任何建议!

您正在执行类文件中的代码。

new_game = ConnectFour.new
new_game.play_game

这将在您每次加载文件时运行,例如在测试时。 它将提示输入并运行gets 它得到的是测试文件的代码(出于某些 rspec 原因)。 这是无效的,所以它会一直运行gets直到最终没有更多输入gets返回nil

从你的类文件中删除它。 像这样的代码应该在一个需要该类的单独文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM