DEV Community

Shivashankar
Shivashankar

Posted on

RSpec - test console input and output

Testing the ruby console input (gets) and output (puts) using RSpec is pretty simple.

Testing gets input
   total = gets.to_i

# Rspec

  allow($stdin).to receive(:gets).and_return(4)
  total = $stdin.gets.to_i

  it "should return received input" do
    expect(total).to eql 4 
  end
Testing puts

Assume we need to test the following output by puts method

   def recently_published_books
     puts "==== Recently Published Books ===="
     puts "1. Atomic Habits"
     puts "2. Intelligent Investor"  
  end   

Rspec to test the above puts output

   msg = <<~PUBLISHED
      ==== Recently Published Books ====
      1. Atomic Habits
      2. Intelligent Investor 
    PUBLISHED

   it "should display the recently published books" do
     expect { recently_published_books }.to output(msg).to_stdout 
   end

Oldest comments (0)