2017-09-07 4 views
0

この単純なコマンドラインゲームのテストで問題が発生しています。私のテスト:「取得」メソッドをスタブしたときにnilを文字列に暗黙的に変換しない

it 'should ask the user name' do 
    allow(@game).to receive(:get_name) { 'Patrick'} 
    expect{@game.show_name}.to output("Your name is Patrick.\n").to_stdout 
end 

私のコード:

def get_name 
    @name = gets.chomp 
end 

    def show_name 
    puts 'Your name is ' + @name + '.' 
    end 

エラーメッセージ:

1)ゲームのセットアップは、ユーザー名 失敗/エラーを依頼する必要がありますプット 'あなたの名前は' + @name + '。'

あなたのコードに変更し

あなたがちょうどgets.chomp

への入力を制御する必要が get_nameスタブする必要はありません
TypeError: 
    no implicit conversion of nil into String 
# ./lib/game.rb:24:in `+' 
# ./lib/game.rb:24:in `show_name' 
# ./spec/game_spec.rb:12:in `block (4 levels) in <top (required)>' 
# ./spec/game_spec.rb:12:in `block (3 levels) in <top (required)>' 
+0

あなたは ':get_name'を受け取りますが、実際にはどこでも呼び出すことはできません –

答えて

0

...

def get_name 
    @name = $stdin.gets.chomp 
end 

次に、あなたのテストをする必要があります...

require 'stringio' 


describe 'test game' do 

    before do 
    $stdin = StringIO.new("Patrick\n") 
    end 

    after do 
    $stdin = STDIN 
    end 

    it 'should ask the user name' do 
    @game.get_name 
    expect{@game.show_name}.to output("Your name is Patrick.\n").to_stdout 
    end 

end 
関連する問題