听闻过TDD有一些时日了,加上之前看过的《敏捷开发的艺术》,是时候试着用这种方法来写一个程序。于是就谷歌到了ruby rspec,同是敏捷开发,但是却是BDD——行为驱动开发。
来自*的简述
BDD的做法包括:
- 确立不同利益相关者要实现的远景目标
- 使用特性注入方法绘制出达到这些目标所需要的特性
- 通过由外及内的软件开发方法,把涉及到的利益相关者融入到实现的过程中
- 使用例子来描述应用程序的行为或代码的每个单元
- 通过自动运行这些例子,提供快速反馈,进行回归测试
- 使用“应当(should)”来描述软件的行为,以帮助阐明代码的职责,以及回答对该软件的功能性的质疑
- 使用“确保(ensure)”来描述软件的职责,以把代码本身的效用与其他单元(element)代码带来的边际效用中区分出来。
- 使用mock作为还未编写的相关代码模块的替身
手头上的工具及书籍包含以下(转载保留 Phodal's Blog Phodal's zenthink)
- 《Ruby元编程》
- 《Programming Ruby》
- 《重构:改善既有代码的设计》
- Mint Linux以及OpenSUSE Linux
- 《测试驱动开发的艺术》
Ruby Rspec
官方的介绍如下RSpec is testing tool for the Ruby programming language. Born under the banner of Behaviour-Driven Development, it is designed to make Test-Driven Development a productive and enjoyable experience with features like:
- a rich command line program (the rspec command)
- textual descriptions of examples and groups (rspec-core)
- flexible and customizable reporting
- extensible expectation language (rspec-expectations)
- built-in mocking/stubbing framework (rspec-mocks)
- 丰富的命令行程序(the rspec command)
- 实例和组文字说明(rspec-core)
- 灵活和可定制的报告
- 可扩展的期望语言(rspec-expecation)
- 内置mocking/stubbing框架(rspec-mocks)
sudo apt-get install ruby-rspec
实际上我觉得还是用
gem install rspec
因为直接用Mint Linux上面的命令带来另外两个版本的ruby,最后在安装rails的时候,问题终于爆发了。
Ruby Rspec BDD
这部分参考了这里的文章使用 RSpec 进行行为驱动测试
这里讲到的思想和TDD很像,也就是不断地通过测试。添加任务到Rakefile
require 'rspec/core/rake_task'
task :default => :spec
desc "run all examples."
RSpec::Core::RakeTask.new(:spec)
创建目录spec
mkdir spec
gedit spec/spec_helper.rb
用来集中使用到的库
添加一个简单的类的测试
require 'spec_helper'
describe Hotel do
let(:hotel){Hotel.new("Photel",3,110)}
it "should return countcost of final" do
hotel.name.should be_a String
end
end
创建一个简单的类来通过测试
class Hotel
def initialize(name,rating,price)
@name=name
@rating=rating
@price=price
end
end
rake
这样的迭代过程用来开发程序算是一件不错的事。