rails测试之RSpec环境搭建

bin/guard init spork  #这一步将产生一个Guardfile文件
bin/guard init rspec  #先运行spork,这样Guardfile中spork位于前面,否则会出错。

 

 

由于编程都是自学的,应用程度不高,很长一段时间都对测试方面避而不见。但看网上很多大牛都推崇“行为驱动开发”(Behavior-driven development),决定也尝试一把。

本文严格说算不上原创,因为基本都是从网上学习来的,思考的余地不大。感谢网络,让俺们也能搞定这种复杂而且先进的流程。

环境: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
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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值