Arman Jon Villalobos Arman Jon Villalobos - 4 months ago 18
Ruby Question

Rspec 3 stubbing user input

Question: What modification I need to do, so that my test results in the command line will be tidy up instead of my print statement being displayed.

I have this class:

class Hello
attr_accessor :name

def say
print "What is your name? "
@name = gets.chomp
end
end


I want to this if it stores the user input name in the
@name
.

My current test works:

it "stores the user's name to a `name` instance variable" do
greeting = Hello.new

allow(greeting).to receive(:gets).and_return("Brian")
greeting.say

expect(greeting.name).to eq "Brian"
end


But it pollutes my output and also requires me to press enter.

Randomized with seed 40671

.**What is your name? .

Pending: (Failures listed here are expected and do not affect your suite's status)

1) Hello#say outputs a greeting including the user's name
# Temporarily skipped with xit
# test/saying_hello_spec.rb:20

2) Hello#say outputs the user's name in capitalize format
# Temporarily skipped with xit
# test/saying_hello_spec.rb:23


Finished in 2.03 seconds (files took 0.10072 seconds to load)
4 examples, 0 failures, 2 pending

Randomized with seed 40671

Answer

In order to silence test results from appearing in the command line when you run specs, you can stub out $stdout's output stream:

before do
  allow($stdout).to receive(:write)
end

In order to send a return character with your stubbed input, you'll need to provide it with a newline character:

allow(greeting).to receive(:gets).and_return("Brian\n")