本文严格说算不上原创,因为基本都是从网上学习来的,思考的余地不大。感谢网络,让俺们也能搞定这种复杂而且先进的流程。
环境:ubunut12.04, ruby1.9.3-p327, rails3.2.11
第一步:创建测试App,使用默认的sqlite3
rails new test-app --skip-test-unit --skip-bundle
这里忽略了默认的单元测试生成和bundle安装
第二步:使用git进行版本管理,由于本项目后续可能会继续测试方面的学习。
git init
vim .gitignore
mv README.rdoc README.md
vim README.md //添加程序说明
git add .
git commit -m "The first commit"
git remote add origin https://github.com/adventurelw/test-app.git
git push -u origin master
第三步:修改Gemfile添加所需要的gem。
https://github.com/adventurelw/test-app/blob/master/Gemfile
第四步:运行bundle
bundle install --binstubs
--binstubs可以将rake命令放进bin目录,使得bundle exec rspec可以bin/rspec来运行。
第五步:运行rspec
rails g rspec:install
这一步将生成spec目录和spec/spec_helper.rb,其中对rspec的配置主要在spec_helper.rb文件。
第六步:运行guard初始化spork和rspec
bin/guard init spork #这一步将产生一个Guardfile文件
bin/guard init rspec #先运行spork,这样Guardfile中spork位于前面,否则会出错。
编辑Guard文件:
添加
require 'active_support/core_ext'
由于不使用cucumber,所以将其相关环境删除。
https://github.com/adventurelw/test-app/blob/master/Guardfile
编辑spec/spec_helper.rb:
添加spork支持。
https://github.com/adventurelw/test-app/blob/master/spec/spec_helper.rb
第七步:运行
bin/guard将会自动启动spork并检测文件变化。
显示以下类似信息则测试环境已经安装成功。
Finished in 0.05937 seconds
0 examples, 0 failures
第八步:对factory_girl进行配置
spec/spec_helper.rb文件RSpec.configure do |config| .. end中添加:
config.include FactoryGirl::Syntax::Methods
config/application.rb中:
config.generators do |g|
g.fixture_replacement :factory_girl, :dir => 'spec/factories'
end
第九步:配置capybara
spec/spec_helper.rb文件require 'rspec/autorun'后:
require 'capybara/rspec'
require 'capybara/rails'
当运行如下命令产生测试文件或者默认生成集成测试时:
rails g integration_test xxxx
将会在spec目录下生成requests目录包含相关测试文件,这时需要添加如下代码到spec/spec_helper中,否则会出现visit这些方法未定义的情况,,features目录不需要这个,并且capybara2以上默认是在features测试,所以下面的代码并不推荐。
RSpec.configure do |config|
config.include Capybara::DSL, :example_group => {
:file_path => "spec/requests"
}
end
第十步:配置simplecov
在spec/spec_helper.rb最上边添加:
require 'simplecov'
SimpleCov.start 'rails'
第十一步:配置database_cleaner
在spec/spec_helper.rb中config.order="random"下添加:
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end