gpt4 book ai didi

ruby - rspec 进行输出测试

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:09 26 4
gpt4 key购买 nike

我无法理解如何使用 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 代码以反射(reflect)我根据在其他地方找到的建议对我的测试文件所做的更改。为了完全解决这个问题,我在我的主文件中使用了 Chris Heald 建议的更改。谢谢大家,谢谢克里斯。

最佳答案

你的初始化器应该是:

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只生成reader方法)

因此,由于您从未分配 @game_output,您的 game_output 方法将始终返回 nil。

关于ruby - rspec 进行输出测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17711744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com