RSpec + Spork + Autotest 给Rails 3添加快速自动化测试
1、新建工程時不使用test-unit
rails new myapp --skip-test-unit
2、添加gem
修改Gemfile
group :development, :test do gem 'rspec-rails' #會自動引用RSpec gem 'spork' #引入Spork gem "autotest-rails" #與ZenTest一起實現自動化測試 gem "ZenTest" end
安裝
bundle install
3、配置rspec
rails generate rspec:install
會生成以下文件:
.rspec rspec配置。
spec/ 所有測試都在這個目錄。
spec/spec_helper.rb
此時即可”bundle exec rspec spec/”或“rake”來執行RSpec測試。
4、Spork加速原理
RSpec默認每執行一次都要加載一次工程環境初始化一些數據,這要耗費很長時間。Sprok啟動時會自動加載工程環境,然后生成幾個fork分支,以DRb形式可供RSpec調用。所有在RSpec執行時就不必再重新加載工程環境。
5、安裝Spork
spork --bootstrap
輸出
Using RSpec Bootstrapping /Users/peter/dev/rails/myapp/spec/spec_helper.rb. Done. Edit /Users/peter/dev/rails/myapp/spec/spec_helper.rb now with your favorite text editor and follow the instructions.
上面做的就是修改spec/spec_helper.rb文件,在其頭部添加了兩段方法。Spork.prefork(只在啟動時執行一次)和Spork.each_run(每次被RSpec調用時均被執行)。
6、修改RSpec配置,實現RSpec與Sprok交互
繼續修改spec/spec_helper.rb,修改后大概如下:
require 'spork'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :rspec
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
end
end
Spork.each_run do
load "#{Rails.root}/config/routes.rb"
Dir["#{Rails.root}/app/**/*.rb"].each { |f| load f }
end
7、告訴RSpec我們使用的Spork
修改”.rspec”文件,在其中添加–drb,修改后”.rspec”的如下:
--colour --drb
8、此時RSpec與Spork即可完美結合了
啟動Spork方法
Spork
執行RSpec方法
bundle exec rspec spec/
此時會發現RSpec執行時間明顯縮短了。但如果通過執行”rake”來啟動RSpec,仍然會很慢,這是因為rake啟動時會加載工程環境,為所有tasks做準備。
9、添加Autotest自動執行測試
啟動Autotest
bundle exec autotest
Autotest就會自動啟動,并監聽文件變化,一旦改變,會立即執行改變部分相關的測試。
添加Autotest是最簡單的,這是因為RSpec內部已經添加了對Autotest的一些支持,也是Rspec Rails推薦的做法。
簡單也有一些問題,如Autotest自定義性不強,不夠靈活。如果你追求自定義那就用Guard吧。
10、一個陷阱
此時當你修改app/models/person.rb時,可能并不會自動執行RSpec測試,這是因為Rails 的test環境默認對class做了緩存。
修改“config/environments/test.rb”
#config/environments/test.rb #config.cache_classes = true #change this line to config.cache_classes = false
參考鏈接:
autotest-rails:https://github.com/seattlerb/autotest-rails
rspec-rails:https://github.com/rspec/rspec-rails
Guard:https://github.com/guard/guard
Spork + Rails 3 + RSpec + Autotest + Growl實現Mac下快速自動化測試并Growl通知測試結果
http://mikbe.tk/2011/02/10/blazingly-fast-tests/
Spork + Rails 3 + RSpec + Watchr測試
http://www.rubyinside.com/how-to-rails-3-and-rspec-2-4336.html
Spork + Rails 3+ Cucumber + RSpec
http://chrismdp.github.com/2010/11/getting-spork-working-now-on-rails-3-rspec-2-and-cucumber/
總結
以上是生活随笔為你收集整理的RSpec + Spork + Autotest 给Rails 3添加快速自动化测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CL_BSP_WD_VIEW_MANAG
- 下一篇: 陈建军:中国商业航天正从战略新兴领域进入