Arman Jon Villalobos Arman Jon Villalobos - 1 year ago 114
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

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

My current test works:

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

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

expect( eq "Brian"

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 Source

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)

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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download