Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write an RSpec test for a Ruby method that contains "gets.chomp"? [duplicate]

Tags:

ruby

rspec

Challenge

Hi! For the following Ruby method, how might I simulate user input using an RSpec test without rewriting the method?

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

I've found a similar question, but this approach requires creating using a class. Does RSpec support stubbing for methods not in a class?

A different works, but I'm forced to rewrite the method

I can rewrite the method so it has a variable with the default value of "gets.chomp" like this:

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

Now I can write an RSpec test like this:

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
like image 539
popedotninja Avatar asked Jun 23 '13 07:06

popedotninja


1 Answers

You can stub out standard input stream like this:

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
like image 180
Victor Deryagin Avatar answered Oct 05 '22 03:10

Victor Deryagin