2013-07-17 181 views
1

我無法理解如何使用puts測試輸出。我需要知道我需要在我的RSPEC文件中做什麼。rspec輸出測試

這是我RSPEC文件:

require 'game_io' 
require 'board' 


describe GameIO do 
    before(:each) do 
    @gameio = GameIO.new 
    @board = Board.new 
    end 

    context 'welcome_message' do 
    it 'should display a welcome message' do 
     test_in = StringIO.new("some test input\n") 
     test_out = StringIO.new 
     test_io = GameIO.new(test_in, test_out) 

     test_io.welcome_message 
     test_io.game_output.string.should == "Hey, welcome to my game. Get ready to be defeated" 
    end 
    end 

end 

這是該文件是針對測試:

class GameIO 
    attr_reader :game_input, :game_output 
    def initialize(game_input = $stdin, game_output = $stdout) 
    @stdin = game_input 
    @stdout = game_output 
    end 


    def welcome_message 
    output "Hey, welcome to my game. Get ready to be defeated" 
    end 


    def output(msg) 
    @stdout.puts msg 
    end 

    def input 
    @stdin.gets 
    end 

end 

注:我更新了我的RSPEC代碼,以反映我對給我的測試文件所做的更改在別處找到的建議爲了完全解決這個問題,我使用了我的主文件中Chris Heald提出的修改。謝謝大家,謝謝克里斯。

+0

以供將來參考:一旦你已經解決了這個問題,這是更好地把解決方案中的答案,而不是編輯你的問題。如果有人回到這個問題,很難看出原來的問題是什麼。 :) – henrikhodne

回答

2

你的初始化應該是:

def initialize(game_input = $stdin, game_output = $stdout) 
    @game_input = game_input 
    @game_output = game_output 
end 

這樣做的原因是,attr_accessor產生這樣的方法:

# attr_accessor :game_output 
def game_output 
    @game_output 
end 

def game_output=(output) 
    @game_output = output 
end 

(attr_reader只生成讀取器方法)

因此,由於您從未指定@game_output,因此您的game_output方法將始終返回nil。

+0

這是最有幫助的提示..我也必須修改我的測試以及...我會嘗試更新我的代碼以反映更改 – Jessi

2

只需選中要發送它的消息:

@gameio.should_receive(:puts).with("Hey, welcome to my game. Get ready to be defeated") 
0

你可以存根和打印。

也許最基本的方法是暫時將STDOUT重新分配給一個變量,並確認該變量與您期望的輸出相匹配。

而Minitest有must_output作爲斷言/規範。

的代碼是這樣的:

## 
# Fails if stdout or stderr do not output the expected results. 
# Pass in nil if you don't care about that streams output. Pass in 
# "" if you require it to be silent. Pass in a regexp if you want 
# to pattern match. 
# 
# NOTE: this uses #capture_io, not #capture_subprocess_io. 
# 
# See also: #assert_silent 

def assert_output stdout = nil, stderr = nil 
    out, err = capture_io do 
    yield 
    end 

    err_msg = Regexp === stderr ? :assert_match : :assert_equal if stderr 
    out_msg = Regexp === stdout ? :assert_match : :assert_equal if stdout 

    y = send err_msg, stderr, err, "In stderr" if err_msg 
    x = send out_msg, stdout, out, "In stdout" if out_msg 

    (!stdout || x) && (!stderr || y) 
end 
+0

我明確需要rspec。但是,謝謝。 – Jessi

+0

好吧,是的。但是絕對沒有理由不能使用上面的代碼,它只是簡單的Ruby。 「def是我們的存根」吧?但存根確實來自RSpec庫。我只是想說明如何使用普通的Ruby,沒有框架。甚至補丁Rspec,畢竟它只是普通的Ruby。正如你從接受的答案中看到的那樣......它大部分是相同的,對吧? – vgoff