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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With