2016-07-31 77 views
0

問題:我需要做什麼修改,以便我的測試結果在命令行中將被整理,而不是顯示我的打印語句。Rspec 3 stubbing用戶輸入

我有這個類:

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 

但是它污染我的輸出,並要求我按enter鍵。

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 

回答

0

爲了出現在當您運行規範的命令行沉默的測試結果,您可以存根出$stdout的輸出流:

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

爲了發送一個回車符與殘缺的輸入,你需要提供一個換行符:

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

謝謝保羅。這工作和簡潔的答案。 –

+0

@ArmanJonVillalobos請考慮接受我的答案(點擊評分下方的「✓」):) –