0

我很难为我的 draw_three_by_three 方法创建测试......这是我的代码......下面我将列出我的测试代码不起作用......你能帮我解决这个问题吗?

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 个失败

4

1 回答 1

0

有关如何测试输出的提示,如果确实有必要,请查看 Ruby 中称为 Minitest 的内置测试框架。它具有使这种测试变得容易 的断言/规范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
于 2013-07-15T22:00:38.997 回答