Why RSpec?
Clear, concise and readable
Gems
.rspec
.rspec-core
.rspec-expectations
.rspec-mocks
.rspec-rails
Basics
Contexts
Describing methods
Running
rspec spec/
Formatters
echo --colort > .rspec
测试运行时附加参数
--colour 为测试输出加颜色
--format o 列出测试时间
--format html:test.html 输出测试文档到test.html
--diff 如测试失败,以diff模式查看期望结果和所得结果的不同
Documentation
rspec -f doc spec/
rspec -f Fuubar -f html -o specs.html spec/
Pending
Filtering by tag
Filtering by tag value
Setup and teardown
Expectations
Built-in matchers
Mocks and stubs
详情参考:
http://kerryb.github.com/iprug-rspec-presentation
rails 测试
rspec替换rails原有的Test:Unit
rails g rspec:install
.create .rspec
.create spec
.create spec/spec_helper.rb (该文件会在每个spec执行时被调用,设置了测试变量,并包含项目级别的RSpec配置项目,加载引用文件等等)
run: rake spec
run: rake spec:model
run: time rake spec:model
factory girl
gem 'factory gril', :git => 'git://github.com/thoughtbot/factory_girl.git', :branch => 'rails3'
add: spec/spec_helper.rb require 'factory_girl'
mkdir spec/factories
cucumber-Rails
It contains 2 generators - one for bootstrapping your Rails app for Cucumber, and a second one for generating features.
Installation
gem 'cucumber-rails'
gem 'capybara'
gem 'database_cleaner'
bootstrap your rails app
rails g cucumber:install --help
rails g cucumber:install
generating a cucumber feature
rails g cucumber:feature post title:string body:text published:boolean
rails g scaffold post title:string body:text published:boolean
rake db:migrate
rake cucumber
查看cucumber语言支持
cucumber --i18n help
cucumber --i18n zh-CN
中文写cucumber可以参考:
https://github.com/aslakhellesoy/cucumber/tree/master/examples/i18n/zh-CN
辅助工具:
会自动监视你的代码的改动,自动运行测试,所以你只要开一个窗口就好
autotest
run: autotest
或
watchr
需要自己手工写.watchr 或 watchr.rb文件
run: watch .watchr 或 watchr.rb
spork
让spec运行快起来
webrat or capybara
模拟浏览器
可以参考rails模板:
https://github.com/oldumy/rails3-app-template
测试相关:
自动生成测试文档
通过附加参数 --format specdoc 每次测试时在终端输出测试文档
spec spec/models/blog_spec.rb --format specdoc
也可以使用rake spec:doc在终端生成全部测试代码的文档
也可以使用--format html将测试文档输出到指定html文件
spec spec/models/blog_spec.rb --format html:test.html
生成覆盖率
利用rcov生成代码覆盖率
rake spec:rcov
会生成html格式的代码覆盖率文档
通过配置spec/rcov.opts来过滤其他代码覆盖率的干扰
--exclude "spec/*, gems/*, app/controllers/*, app/helpers/*, lib/*"
ps:
http://mikbe.tk/2011/02/10/blazingly-fast-tests/
http://www.claytonlz.com/index.php/2010/03/zero-to-tested-with-cucumber-and-factory-girl/
http://www.iteye.com/topic/417899
http://www.anthonyeden.com/2010/11/testing-rest-apis-with-cucumber-and-rack-test/
guard
yajl
acts as api
lambda
acts_as_api