RSpec:我如何编写一个需要特定输出但不关心方法的测试? [英] RSpec: how do I write a test that expects certain output but doesn't care about the method?
问题描述
我正在尝试了解测试驱动设计,特别是 RSpec.但是我遇到了 The RSpec Book 中的一些示例的问题.
I'm trying to get my head around test-driven design, specifically RSpec. But I'm having trouble with some of the examples from The RSpec Book.
在本书中,我们像这样测试 $STDOUT 上的输出:
In the book, we test for output on $STDOUT like this:
output = double('output')
game = Game.new
output.should_receive(:puts).with('Welcome to Codebreaker!')
game.start()
嗯,这是一种时尚.但是我到底为什么要关心 Game 对象是否使用 puts() 方法?如果我把它改成print(),它真的会破坏测试吗?而且,更重要的是,这是否违背了 TDD 的原则之一——我应该测试方法的作用(设计)而不是它是如何做到的(实现)?
Well, that works after a fashion. But why on earth should I care if the Game object uses the puts() method? If I change it to print(), should it really break the test? And, more importantly, isn't this against the one of the principals of TDD - that I should be testing what the method does (the design) rather than how it does it (the implementation)?
有什么方法可以编写一个测试,只测试 $STDOUT 上的结果,而不查看是什么方法将它放在那里?
Is there some way I can write a test that just tests what ends up on $STDOUT, without looking at what method puts it there?
推荐答案
查看 这篇文章.Nick 就同一个例子提出了问题,评论中出现了一段非常有趣的对话.希望对您有所帮助.
take a look at this post. Nick raised questions about the same example, and a very interesting conversation follows in the comments. Hope you find it helpful.
这篇关于RSpec:我如何编写一个需要特定输出但不关心方法的测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!