Ruby 开发中的测试、基准测试与性能分析
1. 测试驱动开发(TDD)
测试驱动开发(TDD)是一种开发技术,开发者在编写系统代码之前先创建一组测试用例,然后严格使用这些测试来维护代码的完整性。它也可以指为任何代码实现测试的技术,即使不一定在编写被测试代码之前创建测试。
下面通过一个简单的例子来说明 TDD 的重要性。我们想要为 String 类添加一个 titleize 方法,将字符串转换为标题格式,例如将 “this is a test” 转换为 “This Is A Test”。
首先,我们可能会这样实现 titleize 方法:
class String
def titleize
self.capitalize
end
end
然后运行测试:
puts "this is a test".titleize
输出结果是 “this is a test”,这显然不是我们期望的结果。
使用 TDD,我们可以先编写测试用例:
raise "Fail 1" unless "this is a test".titleize == "This Is A Test"
raise "Fail 2" unless "another test 1234".title
超级会员免费看
订阅专栏 解锁全文
1092

被折叠的 条评论
为什么被折叠?



