Gtchweb
Gtchweb

Reputation: 69

RSpec asking for user input

I have two questions. Given the ruby code below, what kind of tests would your write in RSpec and how would you avoid when running tests to keep get asked for the user input? I have tried many ways such as:

  1. allow($stdout)
  2. allow(Kernel)
  3. stub(:gets)
  4. STDOUT.should_receive(:puts).with("exit")
  5. allow($stdin).to receive(:gets).and_return('no_gets')
  6. allow_any_instance_of(Kernel).to receive(:gets).and_return('exit')

But non of the above worked. In test kept asking me for the user input.

 class EchoApp
   def greeting
     while(true)
      puts "Say something:"
      user = gets.chomp
      break if user == 'exit'
    end
   return "Goodbye!"
  end
end

Upvotes: 0

Views: 1783

Answers (1)

zeitnot
zeitnot

Reputation: 1314

Your suggestions should work actually. But there is another option.

orig_stdin = $stdin 
$stdin = StringIO.new('exit') 
assert(EchoApp.new.greeting,'Goodbye!')
# Or 
expect(EchoApp.new.greeting).to eql('Goodbye!')
$stdin = orig_stdin

Let me know if this does not work.

Upvotes: 2

Related Questions