DEV Community

Shivashankar
Shivashankar

Posted on

1

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

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay