Ruby rspec中的测试获取(用户输入)
我的类有一个#run方法,到目前为止就是这样,用来测试测试:Ruby rspec中的测试获取(用户输入),ruby,rspec,mocking,Ruby,Rspec,Mocking,我的类有一个#run方法,到目前为止就是这样,用来测试测试: def run puts "Enter 'class' to create a new class." input = $stdin.gets.chomp binding.pry 在目前的测试中,我得到了 allow($stdin).to receive(:gets).and_return 'class' cli.run 通过这种方式,我可以在pry会话中看到,输入已按预期设置为“类” 有没有一种方
def run
puts "Enter 'class' to create a new class."
input = $stdin.gets.chomp
binding.pry
在目前的测试中,我得到了
allow($stdin).to receive(:gets).and_return 'class'
cli.run
通过这种方式,我可以在pry会话中看到,输入
已按预期设置为“类”
有没有一种方法可以在不向方法本身中对get
的调用中添加$stdin
的情况下进行处理?i、 例如,input=gets.chomp
我尝试了allow(cli.run.)。接收(:get)。并返回'class'
但是在pry会话中,
输入
等于spec文件的第一行 您可以这样避免:
def run
puts "Enter 'class' to create a new class."
input = gets.chomp
end
describe 'gets' do
it 'belongs to Kernel' do
allow_any_instance_of(Kernel).to receive(:gets).and_return('class')
expect(run).to eq('class')
end
end
方法获取
实际上属于内核
模块。(方法(:gets).owner==内核
)。由于Kernel
包含在Object
中,并且几乎所有ruby对象都继承自Object
,因此这将起作用
现在,如果run
是一个在类
中作用域的实例方法,我建议对存根的作用域进行更多的限定,以便:
class Test
def run
puts "Enter 'class' to create a new class."
input = gets.chomp
end
end
describe 'gets' do
it 'can be stubbed lower than that' do
allow_any_instance_of(Test).to receive(:gets).and_return('class')
expect(Test.new.run).to eq('class')
end
# or even
it 'or even lower than that' do
cli = Test.new
allow(cli).to receive(:gets).and_return('class')
expect(cli.run).to eq('class')
end
end
谢谢allow(cli).to receive(:gets).and_return('class')
正是我一直在寻找的东西,它很有效。