How to write an RSpec test for a Ruby method that contains "gets.chomp"?

Problem

Hello! For the next Ruby method, how can I simulate user input using the RSpec test without overwriting the method?

def capture_name puts "What is your name?" gets.chomp end 

I found a similar question , but this approach requires creating using a class. Does RSpec support stubbing for methods outside the class?

Various works, but I have to rewrite the method

I can rewrite the method so that it has a variable with the default value "gets.chomp" as follows:

 def capture_name(user_input = gets.chomp) puts "What is your name?" user_input end 

Now I can write the RSpec test as follows:

 describe "Capture name" do let(:user_input) { "James T. Kirk" } it "should be 'James T. Kirk'" do capture_name(user_input).should == "James T. Kirk" end end 
+6
source share
1 answer

You can drown out the standard input stream as follows:

 require 'stringio' def capture_name $stdin.gets.chomp end describe 'capture_name' do before do $stdin = StringIO.new("James T. Kirk\n") end after do $stdin = STDIN end it "should be 'James T. Kirk'" do expect(capture_name).to be == 'James T. Kirk' end end 
+19
source

Source: https://habr.com/ru/post/947926/


All Articles