Rspec 3存根用户输入

时间:2016-07-31 00:23:31

标签: ruby rspec

问题:我需要做哪些修改,以便我在命令行中的测试结果将会整齐,而不是显示我的print语句。

我有这堂课:

class Hello
  attr_accessor :name

  def say
    print "What is your name? "
    @name = gets.chomp
  end
end

如果它将用户输入名称存储在@name

中,我想这样做

我目前的测试工作:

it "stores the user's name to a `name` instance variable" do
  greeting = Hello.new

  allow(greeting).to receive(:gets).and_return("Brian")
  greeting.say

  expect(greeting.name).to eq "Brian"
end

但它会污染我的输出,也需要我按回车。

Randomized with seed 40671

.**What is your name? .

Pending: (Failures listed here are expected and do not affect your suite's status)

  1) Hello#say outputs a greeting including the user's name
     # Temporarily skipped with xit
     # test/saying_hello_spec.rb:20

  2) Hello#say outputs the user's name in capitalize format
     # Temporarily skipped with xit
     # test/saying_hello_spec.rb:23


Finished in 2.03 seconds (files took 0.10072 seconds to load)
4 examples, 0 failures, 2 pending

Randomized with seed 40671

1 个答案:

答案 0 :(得分:1)

为了在运行规范时使测试结果无法在命令行中显示,您可以存根$stdout的输出流:

before do
  allow($stdout).to receive(:write)
end

为了使用存根输入发送返回字符,您需要为其提供换行符:

allow(greeting).to receive(:gets).and_return("Brian\n")