在RSpec中创建消息期望是否可以消除控制台上传递的测试残留消息?

时间:2016-05-24 00:06:26

标签: ruby rspec

在我的班上,我有一个方法。在else块中,它会显示一条消息“你输入的号码甚至不在卡片上......”以及该卡的副本。

def is_input_valid?(input)
   if current_card.include?(input.first) && current_card.include?(input.last) 
      true
   else 
      puts "A number you typed isn't even on the card..."
      p current_card
      false
   end
end 

在我的测试中,我故意让方法转到else块然后通过。

it "returns false if input contains ANY numbers NOT from the current_card" do
   allow(deck).to receive(:gets) {"99/99"}
   deck.get_player_input

   expect(deck.is_input_valid?(deck.player_input)).to be(false)
end

在我的控制台上,我明白了:

...............A number you typed isn't even on the card...
[6, 6, 6, 6]
.

Finished in 0.026 seconds (files took 0.62704 seconds to load)
16 examples, 0 failures

测试通过,但我不想看到这一点。我该如何摆脱它?

...............A number you typed isn't even on the card...
    [6, 6, 6, 6]

1 个答案:

答案 0 :(得分:2)

最好的方法是在本地测试STDOUT流静音, 在spec_helper.rb

def suppress_output
  allow(STDOUT).to receive(:puts) # this disables puts
end

在测试中

RSpec.describe SomeClass do
  before do
    suppress_output
  end
end

如果您使用的是Rails,请使用silence_stream

it "returns false if input contains ANY numbers NOT from the current_card" do
  allow(deck).to receive(:gets) {"99/99"}
  silence_stream(STDOUT) do
     deck.get_player_input
     expect(deck.is_input_valid?(deck.player_input)).to be(false)
  end
end

或全球(Rspec 3 +)

RSpec.configure do |c|
  c.before { allow($stdout).to receive(:puts) }
end