自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

高效的單元測試Rails該怎樣進行

開發(fā) 測試
主要介紹如何高效的進行單元測試Rails,希望對你有幫助,一起來看。

在筆者開發(fā)的系統(tǒng)中,有大量的數(shù)據(jù)需要分析,不僅要求數(shù)據(jù)分析準確,而且對速度也有一定的要求的。沒有寫測試代碼之前,筆者用幾個很大的方法來實現(xiàn)這種需求。結果可想而知,代碼繁雜,維護困難,難于擴展。借業(yè)務調整的機會,筆者痛定思痛,決定從測試代碼做起,并隨著不斷地學習和應用,慢慢體會到測試代碼的好處。

  • 改變思路:能做到從需求到代碼的過程轉換,逐步細化;
  • 簡化代碼:力圖讓每個方法都很小,只專注一件事;
  • 優(yōu)化代碼:當測試代碼寫不出來,或者需要寫很長的時候,說明代碼是有問題的,是可以被分解的,需要進一步優(yōu)化;
  • 便于擴展:當擴展新業(yè)務或修改舊業(yè)務時,如果測試代碼沒有成功,則說明擴展和修改不成功;
  • 時半功倍:貌似寫測試代碼很費時,實際在測試、部署和后續(xù)擴展中,測試代碼將節(jié)省更多的時間。

環(huán)境搭建

筆者采用的測試環(huán)境是比較流行通用的框架:RSpec + Factory Girl,并用autotest自動工具。RSpec是一種描述性語言,通過可行的例子描述系統(tǒng)行為,非常容易上手,測試用例非常容易理解。Factory Girl可以很好的幫助構造測試數(shù)據(jù),免去了自己寫fixture的煩惱。Autotest能自動運行測試代碼,隨時檢測測試代碼的結果,并且有很多的插件支持,可以讓測試結果顯示的很炫。

第一步 安裝rspec和rspec-rails

在命令行中執(zhí)行如下命令:

 

  1. $ sudo gem install rspec v = 1.3.0  
  2. $ sudo gem install rspec-rails v = 1.3.2 

安裝完成后,進入rails應用所在的目錄,運行如下腳本,生成spec測試框架:

 

  1. $ script/generate rspec   
  2. exists lib/tasks  
  3. identical lib/tasks/rspec.rake  
  4. identical script/autospec  
  5. identical script/spec  
  6. exists spec  
  7. identical spec/rcov.opts  
  8. identical spec/spec.opts  
  9. identical spec/spec_helper.rb 

第二步 安裝factory-girl

在命令行中執(zhí)行如下命令:

 

  1. $ sudo gem install factory-girl 

在config/environment/test.rb中,加入factory-girl這個gem:

 

  1. config.gem "factory_girl" 

在spec/目錄下,增加一個factories.rb的文件,用于所有預先定義的model工廠。

第三步 安裝autotest

在命令行中執(zhí)行如下命令:

 

  1. $ sudo gem install ZenTest  
  2. $ sudo gem install autotest-rails 

然后設置與RSpec的集成,在rails應用的目錄下,運行如下的命令,就可以顯示測試用例的運行結果。

 

  1. RSPEC=true autotest or autospec 

在自己的home目錄下,增加一個.autotest設置所有的Rails應用的autotest插件。當然,也可以把這個文件加到每個應用的根目錄下,這個文件將覆蓋home目錄下的文件設置。autotest的插件很多,筆者用到如下的plugin:

 

  1. $ sudo gem install autotest-growl  
  2. $ sudo gem install autotest-fsevent  
  3. $ sudo gem install redgreen 

設置.autotest文件,在.autotest中,加入如下代碼。

 

  1. require 'autotest/growl'   
  2. require 'autotest/fsevent'   
  3. require 'redgreen/autotest'   
  4. Autotest.add_hook :initialize do |autotest|  
  5. %w{.git .svn .hg .DS_Store ._* vendor tmp log doc}.each do |exception|  
  6. autotest.add_exception(exception)  
  7. end  
  8. end 

 

#p#

測試經驗

安裝了必要的程序庫以后,就可以寫測試代碼了。本例中,所有應用都是在Rails 2.3.4上開發(fā)的,RSpec采用的是1.3.0的版本。為了很好的說明問題,我們假定這樣的需求:判斷一個用戶在一個時間段內是否遲到。寫測試代碼時都是遵循一個原則,只關心輸入和輸出,具體的實現(xiàn)并不在測試代碼的考慮范圍之內,是行為驅動開發(fā)。根據(jù)這個需求,我們將會設計方法absence_at(start_time,end_time),有兩個輸入值start_time和end_time以及一個輸出值,類型是boolean。對應的測試代碼如下:

 

  1. describe "User absence or not during [start_time,end_time]" do  
  2. before :each do   
  3. @user = Factory(:user)  
  4. end 
  5. it "should return false when user not absence " do  
  6. start_time = Time.utc(2010,11,9,12,0,0,0)  
  7. end_time = Time.utc(2010,11,9,12,30,0)   
  8. @user.absence_at(start_time,end_time).should be_false  
  9. end 
  10. it "should return true when user absence " do  
  11. start_time = Time.utc(2010,11,9,13,0,0,0)  
  12. end_time = Time.utc(2010,11,9,13,30,0)   
  13. @user.absence_at(start_time,end_time).should be_ture  
  14. end 
  15. end 

測試代碼已經完成。至于absence_at方法我們并不關心它的實現(xiàn),只要這個方法的結果能讓測試代碼運行結果正確就可以。在此測試代碼的基礎上,就可以大膽地去完成代碼,并根據(jù)測試代碼的結果不斷修改代碼直到所有測試用例通過。

Stub的使用

寫測試代碼,最好首先從model開始。因為model的方法能很好與輸入輸出的原則吻合,容易上手。最初的時候,你會發(fā)現(xiàn)mock和stub很好用,任何的對象都可以mock,并且在它的基礎上可以stub一些方法,省去構造數(shù)據(jù)的麻煩,一度讓筆者覺得測試代碼是如此美麗,一步步的深入,才發(fā)現(xiàn)自己陷入了stub的誤區(qū)。還是引用上面的例子,我們的代碼實現(xiàn)如下:

  1. class User < ActiveRecord::Base 
  2. def absence_at(start_time,end_time)   
  3. return false if have_connection_or_review?(start_time,end_time)  
  4. return (login_absence_at?(start_time,end_time) ? true : false)   
  5. end  
  6. end 

按照最初寫測試代碼的思路,本方法中存在三種情況,即需要三個用例,而且還調用了其他兩個方法,需要對他們進行stub,于是就有了下面的測試代碼。記得當時完成后還很興奮,心中還想:這么寫測試代碼真有趣。

 

  1. before(:each) do  
  2. @user = User.new  
  3. end  
  4. describe "method <absence_at(start_time,end_time)>" do   
  5. s = Time.now  
  6. e = s + 30.minutes  
  7. # example one  
  8. it "should be false when user have interaction or review" do  
  9. @user.stub!(:have_connection_or_review?).with(s,e).and_return(true)  
  10. @user.absence_at(s,e).should be_false  
  11. end  
  12. # example two  
  13. it "should be true when user has no interaction and he no waiting at platform" do  
  14. @user.stub!(:have_connection_or_review?).with(s,e).and_return(false)  
  15. @user.stub!(:login_absence_at?).with(s,e).and_return(true)  
  16. @user.absence_at(s,e).should be_true  
  17. end  
  18. # example three  
  19. it "should be false when user has no interaction and he waiting at platform" do  
  20. @user.stub!(:have_connection_or_review?).with(s,e).and_return(false)  
  21. @user.stub!(:login_absence_at?).with(s,e).and_return(false)  
  22. @user.absence_at(s,e).should be_false  
  23. end   
  24. end 

上面的測試代碼,是典型把代碼的實現(xiàn)細節(jié)帶到了測試代碼中,完全是本末倒置的。當然這個測試代碼運行的時候,結果都是正確的。那是因為用stub來假定所有的子方法都是對的,但是如果這個子方法have_connection_or_review?發(fā)生變化,它不返回boolean值,那么將會發(fā)生什么呢?這個測試代碼依然正確,可怕吧!這都沒有起到測試代碼的作用。

另外,如果是這樣,我們不僅要修改have_connection_or_review?的測試代碼,而且還要修改absence_at的測試代碼。這不是在增大代碼維護量嗎?

相比而言,不用stub的測試代碼,不用修改,如果Factory的數(shù)據(jù)沒有發(fā)生變化,那么測試代碼的結果將是錯誤的,因為have_connection_or_review?沒有通過測試,導致absence_at方法無法正常運行。

其實stub主要是mock一些本方法或者本應用中無法得到的對象,比如在tech_finish?方法中,調用了一個file_service來獲得Record對象的所有文件,在本方法測試代碼運行過程中,無法得到這個service,這時stub就起作用了:

 

  1. class A < ActiveRecord::Base 
  2. has_many :records  
  3. def tech_finish?  
  4. self.records.each do |v_a|  
  5. return true if v_a.files.size == 5  
  6. end  
  7. return false  
  8. end  
  9. end  
  10. class Record < ActiveRecord::Base 
  11. belongs_to :a  
  12. has_files # here is a service in gem  
  13. end 

所對應的測試代碼如下:

 

  1. describe "tech_finish?" do  
  2. it "should return true when A’s records have five files" do  
  3. record = Factory(:record)  
  4. app = Factory(:a,:records=>[record])  
  5. record.stub!(:files).and_return([1,2,3,4,5])   
  6. app.tech_finish?.should == true  
  7. end  
  8. it "should return false when A’s records have less five files" do  
  9. record = Factory(:record)  
  10. app = Factory(:a,:records=>[record])  
  11. record.stub!(:files).and_return([1,2,3,5])   
  12. app.tech_finish?.should == false  
  13. end  
  14. end 

 

Factory的使用

有了這個工廠,可以很方便的構造不同的模擬數(shù)據(jù)來運行測試代碼。還是上面的例子,如果要測試absence_at方法,涉及到多個model:

  • HistoryRecord:User的上課記錄
  • Calendar:User的課程表
  • Logging:User的日志信息

如果不用factory-girl構造測試數(shù)據(jù),我們將不得不在fixture構造這些測試數(shù)據(jù)。在fixture構造的數(shù)據(jù)無法指定是那個測試用例使用,但是如果用Factory的話,可以為這個方法專門指定一組測試數(shù)據(jù)。

 

  1. Factory.define :user_absence_example,:class => User do |user|  
  2. user.login "test"  
  3. class << user 
  4. def default_history_records  
  5. [Factory.build(:history_record,:started_at=>Time.now),  
  6. Factory.build(:history_record,:started_at=>Time.now)]  
  7. end  
  8. def default_calendars  
  9. [Factory.build(:calendar),  
  10. Factory.build(:calendar)]   
  11. end  
  12. def default_loggings  
  13. [Factory.build(:logging,:started_at=>1.days.ago),  
  14. Factory.build(:logging,:started_at=>1.days.ago)]  
  15. end  
  16. end  
  17. user.history_records {default_history_records}  
  18. user.calendars {default_calendars}  
  19. user.loggings {default_loggings}  
  20. end 

這個測試數(shù)據(jù)的構造工廠,可以放在factories.rb文件中,方便其他測試用例使用,也可以直接放到測試文件的before中,僅供本測試文件使用。通過factory的構造,不僅可以為多個測試用例共享同一組測試數(shù)據(jù),而且測試代碼也簡潔明了。

 

  1. before :each do  
  2. @user = Factory.create(:user_absence_example)  
  3. end 

 

#p#

Readonly的測試

在筆者的系統(tǒng)中,大量使用了acts_as_readonly,從另外一個數(shù)據(jù)庫來讀取數(shù)據(jù)。由于這些model并不在本系統(tǒng)中,所以當用Factory構造測試數(shù)據(jù)的時候,總會有問題。雖然也可以使用mock來達到這個目的,但是由于mock的局限性,還是無法靈活的滿足構造測試數(shù)據(jù)的需要。為此,擴展了一些代碼,使得這些model依然可以測試。核心思想則是,根據(jù)配置文件的設置,將對應的readonly的表創(chuàng)建在測試數(shù)據(jù)庫,這個操作在運行測試之前執(zhí)行,這樣就達到與其他model一樣的效果。site_config配置文件中,關于readonly的配置格式如下:

 

  1. readonly_for_test:  
  2. logings:  
  3. datetime: created_at  
  4. string: status  
  5. integer: trainer_id 

Gem的測試

Gem在Rails中被廣泛使用,而且是最基礎的東西,因此它的準確無誤就顯得更加重要。在不斷實踐的基礎上,筆者所在的團隊總結出一種用spec測試gem的方法。假設我們要測試的gem是platform_base,步驟如下:

1. 在gem的根目錄下創(chuàng)建一個目錄spec(路徑為platform_base/spec)。

2. 在gem的根目錄下創(chuàng)建文件Rakefile(路徑為platform_base/Rakefile),內容如下:

 

  1. require 'rubygems'  
  2. require 'rake'  
  3. require 'spec/rake/spectask'  
  4. Spec::Rake::SpecTask.new('spec') do |t|  
  5. t.spec_opts = ['--options', "spec/spec.opts"]  
  6. t.spec_files = FileList['spec/**/*_spec.rb']  
  7. end 

 

3. 文件在spec目錄下創(chuàng)建spec.opts(路徑為platform_base/spec/spec.opts),內容如下:

  1. --colour  
  2. --format progress  
  3. --loadby mtime  
  4. --reverse 

4. 在spec目錄下,創(chuàng)建一個Rails app,名為test_app。這個新應用需要有spec目錄和spec_helper.rb文件。

5. 為了保持簡化,把這個新app(test_app)整理一下,刪除vendor和public目錄,最終的結構如下:

 

  1. test_app  
  2. |- app  
  3. |- config  
  4. | |- environments  
  5. | |- initializers  
  6. | |- app_config.yml  
  7. | |- boot.rb  
  8. | |- database.yml  
  9. | |- environment.rb  
  10. | \- routes.rb  
  11. |- db  
  12. | \- test.sqlite3  
  13. |- log  
  14. \- spec  
  15. \- spec_helper.rb 

6. 在config/environment.rb配置文件中,增加如下代碼:

  1. Rails::Initializer.run do |config|  
  2. config.gem 'rails_platform_base'  
  3. end 

7. 在platform_base/spec/目錄下增加helpers_spec.rb文件,內容如下:

 

  1. require File.join(File.dirname(__FILE__), 'test_app/spec/spec_helper')  
  2. describe "helpers" do  
  3. describe "url_of" do  
  4. before do  
  5. Rails.stub!(:env).and_return("development")  
  6. @controller = ActionController::Base.new  
  7. end 
  8. it "should get url from app's configration" do  
  9. @controller.url_of(:article, :comments, :article_id => 1).should == "http://www.idapted.com/article/articles/1/comments" 
  10. @controller.url_of(:article, :comments, :article_id => 1, :params=>{:category=>"good"}).should == "http://www.idapted.com/article/articles/1/comments?category=good" 
  11. end 
  12. end 
  13. end 

至此,準備工作已經就緒,可以在platform_base目錄下,運行rake spec來進行測試,當然現(xiàn)在什么都不會發(fā)生,因為還沒有測試代碼呢。本方法中,最關鍵的就是下面的require語句,不僅加載了Rails environment,而且把gem在test_app中使用并測試。

 

  1. require File.join(File.dirname(__FILE__), 'test_app/spec/spec_helper') 

#p#

Controller的測試

對于controller的測試,一般來說比較簡單,基本是三段式:初始化參數(shù)、請求方法、返回render或者redirect_to。如下例中,對某個controller的index方法的測試:

  1. describe "index action" do  
  2. it "should render report page with the current month report" do  
  3. controller.stub!(:current_user).and_return(@user)  
  4. get :index,{:flag => “test”}  
  5. response.should render_template("index")  
  6. end  
  7. end 

有些controller會設置session或者flash,這時的測試代碼就一定要檢查這個值設置的是否正確,而且還需要增加測試用例來覆蓋不同的值,這樣才能對方法進行全面的測試。如下例:

 

  1. describe "create action" do  
  2. it "should donot create new user with wrong params" do  
  3. post :create  
  4. response.should redirect_to(users_path)  
  5. flash[:notice].should == "Create Fail!"  
  6. end  
  7.  
  8. it "should create a new user with right params" do  
  9. post :create, {:email => "abc@eleutian.com"}  
  10. response.should redirect_to(users_path)  
  11. flash[:notice].should == "Create Successful!"  
  12. end  
  13. end 

 

同時,也需要對controller的assigns進行測試,以保證返回正確的數(shù)據(jù)。如下例:

 

  1. before(:each) do  
  2. @course = Factory(:course)  
  3. end   
  4. describe "show action" do  
  5. it "should render show page when flag != assess and success" do   
  6. get :show, :id => @course.id, :flag =>"test"  
  7. response.should render_template("show")  
  8. assigns[:test_paper].should == @course  
  9. assigns[:flag].should == "test"  
  10. end  
  11. it "should render show page when flag == assess and success" do  
  12. get :show, :id => @course.id, :flag =>"assess"  
  13. response.should render_template("show")  
  14. assigns[:test_paper].should == @course  
  15. assigns[:flag].should == "assess"  
  16. end   
  17. end 

View的測試

View的測試代碼寫的比較少,基本上是把核心的view部分集成到controller中來測試。主要用integrate_views方法。如下例:

 

  1. describe AccountsController do  
  2. integrate_views  
  3. describe "index action" do  
  4. it "should render index.rhtml" do  
  5. get :index  
  6. response.should render_template("index")  
  7. response.should have_tag("a[href=?]",new_account_path)  
  8. response.should have_tag("a[href=?]",new_session_path)  
  9. end  
  10. end  
  11. end 

總結展望

在寫測試代碼的時候,并不一定要事無巨細,有些比較簡單的方法以及Rails的內部的方法,如named_scope,就完全沒有必要測試。本文中,只介紹了用rspec寫單元測試的代碼,對于集成測試沒有涉及,這也是今后努力的一個方向。

另外,用cumumber + rspec + webrat的BDD開發(fā)模式也是相當不錯的。尤其是cumumber對需求的描述,完全可以用它來做需求分析。

【編輯推薦】

  1. 如何做好單元測試
  2. 淺談軟件測試嵌入式單元測試技能
  3. 單元測試徹底測試的方法
  4. 詳細講解單元測試的內容
  5. 淺談單元測試的意義
責任編輯:于鐵 來源: InfoQ
相關推薦

2017-01-14 23:26:17

單元測試JUnit測試

2017-01-16 12:12:29

單元測試JUnit

2011-11-30 22:03:49

ibmdwJava

2013-06-04 09:49:04

Spring單元測試軟件測試

2017-03-23 16:02:10

Mock技術單元測試

2017-01-14 23:42:49

單元測試框架軟件測試

2012-11-01 11:32:23

IBMdw

2012-11-01 11:37:05

JavaScript單元測試測試工具

2021-03-28 23:03:50

Python程序員編碼

2009-08-19 09:00:48

單元測試框架自動化測試

2021-03-24 09:30:02

Jupyter not單元測試代碼

2023-08-02 13:59:00

GoogleTestCTest單元測試

2023-07-26 08:58:45

Golang單元測試

2011-05-16 16:52:09

單元測試徹底測試

2023-12-11 08:25:15

Java框架Android

2017-12-12 13:17:36

機器學習代碼單元測試

2011-06-14 15:56:42

單元測試

2020-08-18 08:10:02

單元測試Java

2022-05-12 09:37:03

測試JUnit開發(fā)

2021-05-05 11:38:40

TestNGPowerMock單元測試
點贊
收藏

51CTO技術棧公眾號