如何设计RSpec测试以将gets.chomp
方法分配给实例变量?
def choose
puts "Please enter the type you want:"
@type = gets.chomp
puts "Thank you, now please enter how many of those you want:"
@quantity = gets.chomp
end
答案 0 :(得分:2)
您可以使用存根/模拟。但主要问题是:你在哪里放置def choose
?这很重要,因为我会将它调用于某个对象。
假设您在class Item
中使用此方法:
class Item
def choose
puts "Please enter the type you want:"
@type = gets.chomp
puts "Thank you, now please enter how many of those you want:"
@quantity = gets.chomp
end
end
然后我将能够存根gets
和chomp
来模拟用户的输入:
RSpec.describe Item do
describe '#choose' do
before do
io_obj = double
expect(subject)
.to receive(:gets)
.and_return(io_obj)
.twice
expect(io_obj)
.to receive(:chomp)
.and_return(:type)
expect(io_obj)
.to receive(:chomp)
.and_return(:quantity)
end
it 'sets @type and @quantity according to user\'s input' do
subject.choose
expect(subject.instance_variable_get(:@type)).to eq :type
expect(subject.instance_variable_get(:@quantity)).to eq :quantity
end
end
end