How to Test Ruby's Standard Input/Output with RSPEC

Asked 2 years ago, Updated 2 years ago, 96 views

How do I test Ruby's standard input/output with RSpec?

The code to be tested is as follows:

class Sample

  def run
    puts 'Please input your name'

    while input = STDIN.gets.chomp
      break if input=="exit"
      puts "Your name is #{input}"
      puts 'Please input your name'
    end
  end
end

Sample.new.run

When done, it accepts the name entry, displays the name if it is entered, and repeats the process of returning to the name reception in the loop.Exit will skip the process.

$ruby test.rb
Please input your name
Taro
Your name is Taro
Please input your name
Jiro Corporation
Your name is Jiro
Please input your name
exit

I'm writing this RSpec test code, but I'm stuck in an infinite loop, so I can't do it.

describe Sample do
  describe 'run' do

    let(:sample) {Sample.new}

    it's your name'do
      allow(STDIN).to receive(:gets) {'Takashi'}
      expect(STDOUT).to receive(:puts).with('Please input your name')
      sample.run
    end
  end
end

If you put Takashi in the test you want to do, your name is Takashi will succeed.
If you enter exit , it is a test of the that leaves the process out.

What should I do?

ruby-on-rails ruby rspec

2022-09-29 22:03

1 Answers

First, the last line of test.rb is as follows:This is to prevent Sample.new.run from running during testing.

Sample.new.run if $0 ==__FILE__

Also, STDIN.gets returns only 'Takashi' in the current test code.
Try to return 'Takashi' for the first time and 'exit' for the second time.

allow(STDIN).to receive(:gets).and_return 'Takashi', 'exit'

And STDOUT.puts expects only 'Please input your name', so
You can also receive Please input your name and Your name is Takashi.

expect(STDOUT).to receive(:puts).with('Please input your name')
expect(STDOUT).to receive(:puts).with('Your name is Takashi')
expect(STDOUT).to receive(:puts).with('Please input your name')

I think this will work.


2022-09-29 22:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.