我很难为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 spec / 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次失败
答案 0 :(得分: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