Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby rspec中的测试获取(用户输入)_Ruby_Rspec_Mocking - Fatal编程技术网

Ruby rspec中的测试获取(用户输入)

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会话中看到,输入已按预期设置为“类” 有没有一种方

我的类有一个#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会话中看到,
输入
已按预期设置为
“类”

有没有一种方法可以在不向方法本身中对
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')
正是我一直在寻找的东西,它很有效。