2013-07-15 85 views
0

我很難爲我的draw_three_by_three方法創建一個測試......這是我的代碼...下面我將列出我的測試代碼不起作用..你能幫我弄清楚嗎?如何爲此編寫rspec測試

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

    def draw_three_by_three(board) 
    out_board = "\n" 
    out_board << " #{board.grid[0]} | #{board.grid[1]} | #{board.grid[2]}\n" 
    out_board << "-----------\n" 
    out_board << " #{board.grid[3]} | #{board.grid[4]} | #{board.grid[5]}\n" 
    out_board << "-----------\n" 
    out_board << " #{board.grid[6]} | #{board.grid[7]} | #{board.grid[8]} \n" 
    output out_board 
    end 

    def output(msg) 
    stdout.puts msg 
    end 
end 

這裏是我的RSpec的代碼是錯誤的...我如何寫這一個RSpec測試?

require 'game_io' 
require 'board' 

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

    end 

    context 'draw_three_by_three_board' do 
    it 'should display the board on standard output' do 
     @gameio.draw_three_by_three(@board).should == <<-EOF.gsub(/^ {6}/, '') 

     + | + | + 
     ----------- 
     + | + | + 
     ----------- 
     + | + | + 
     EOF 
    end 
    end 
end 

,這是RSpec的錯誤我得到....

$ rspec的投機/ game_io_spec.rb

+ | + | + 
----------- 
+ | + | + 
----------- 
+ | + | + 

F 

失敗:

1) game_io draw_three_by_three_board should display the board on standard output 
    Failure/Error: EOF 
    expected: "\n + | + | +\n-----------\n + | + | +\n-----------\n + | + | + \n" 
      got: nil (using ==) 
    # ./spec/game_io_spec.rb:20:in `block (3 levels) in <top (required)>' 

已完成在0.00074秒 1例如,1個故障

+1

'output'方法不會返回任何東西 - 它只是通過'puts'將它發送到stdout。 – PinnyM

+0

是在控制檯上測試它。 'puts'打印到shell並返回'nil'。 – nicooga

+1

我寧願'draw_three_by_three'只生成一個字符串,但不會將它輸出到標準輸出中,所以對於您的測試,您可以測試此方法。 –

回答

0

對於如何測試輸出的提示,如果確實需要,請查看名爲Minitest的Ruby中的內置測試框架。它有斷言/規格assert_output/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 
相關問題