How to test STDIN with RSpec

Well, you need help developing a test. I want to check that this class gets the letter "O" and that when the "move_computer" method is called, WHATEVER is returned when a person enters cli. my psychic subprocessor tells me that it’s just assigning a variable to something to keep a random human input into STDIN. You just won’t get it right now ... are everyone pointing me in the right direction?

here is my class ...

class Player def move_computer(leter) puts "computer move" @move = gets.chomp return @move end end 

my test looks like ...

 describe "tic tac toe game" do context "the player class" do it "must have a computer player O" do player = Player.new() player.stub!(:gets) {"\n"} #FIXME - what should this be? STDOUT.should_receive(:puts).with("computer move") STDOUT.should_receive(:puts).with("\n") #FIXME - what should this be? player.move_computer("O") end end end 
+3
source share
2 answers

Because move_computer returns the input, I think you wanted to say:

 player.move_computer("O").should == "\n" 

I would write the full specification as follows:

 describe Player do describe "#move_computer" do it "returns a line from stdin" do subject.stub!(:gets) {"penguin banana limousine"} STDOUT.should_receive(:puts).with("computer move") subject.move_computer("O").should == "penguin banana limousine" end end end 
+2
source

Here is the answer I came up with ...

 require_relative '../spec_helper' # the universe is vast and infinite...it contains a game.... but no players describe "tic tac toe game" do context "the player class" do it "must have a human player X"do player = Player.new() STDOUT.should_receive(:puts).with("human move") player.stub(:gets).and_return("") player.move_human("X") end it "must have a computer player O" do player = Player.new() STDOUT.should_receive(:puts).with("computer move") player.stub(:gets).and_return("") player.move_computer("O") end end end 

[NOTE FOR ADMINS ... it would be great if I could just select all the code and right indent with the click of a button. (Hmmm ... I thought it was a feature in the past ...?)]

+1
source

Source: https://habr.com/ru/post/1437190/


All Articles