gpt4 book ai didi

ruby - RSpec 测试包含 gets.chomp 的方法

转载 作者:数据小太阳 更新时间:2023-10-29 09:03:37 24 4
gpt4 key购买 nike

如何设计 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

最佳答案

您可以为此使用 stub /模拟。但主要问题是:您将 def choose 放在哪里?这很重要,因为我会在某些对象上 stub 它的调用。

假设您在 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

然后我将能够 stub getschomp 调用来模拟用户的输入:

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

关于ruby - RSpec 测试包含 gets.chomp 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29323771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com