我无法理解如何使用puts
测试输出。我需要知道在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建议的更改。谢谢大家,谢谢Chris。
答案 0 :(得分:2)
请检查您是否正在向其发送消息:
@gameio.should_receive(:puts).with("Hey, welcome to my game. Get ready to be defeated")
答案 1 :(得分: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。
答案 2 :(得分: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