(軟體工程)【Rails】PSpec Unit Testing

--

簡介:

寫測試UnitTest是一種撰寫自動化測試,寫測試的四大優勢,正確、穩定、設計、文件(測試的時候就已經在設計規格了)。

觀念:

學習Unit Test的必要性、觀念與缺點:觀念就是養成讓自己所寫出來的程式穩定,確定是可以Run的,並且經過設計過的,一步一腳印的”刻出Code代碼”來。

缺點:

缺點就是麻煩、耗時間、不好玩、很無聊,通常在時間比較閒足夠的情況下,好好的來寫UnitTest是最好的,不用UnitTest能不能開發出成品,當然可以,這就叫做手動測試。

Unit Test主要有分四種:

  1. 對Controller測試
  2. 對Models測試
  3. 對Views測試
  4. 對Object測試

安裝方式:

#版本 rails 5.x 以上group :development, :test dogem 'rspec-rails', '~> 5.0.0'endbundle exec rspecbundle exec rspec spec/...bundle exec rspec --helpbundle installrails generate rspec:installbundle update rspec-railsModel ex.:RSpec.describe SystemExit, type: :model doit "should discount five percent SystemExit title" do
system = SystemExit.new( :name => "Title name" )
expect(system)
#expect(system).to eq()
end
end

Rails spec basic code:

require ‘rails_helper’RSpec.describe XXXController, type: :controller do  describe “GET #index” do     it “returns http success” do       get :index       expect(response).to have_http_status(:success)     end  endend

Output:

#表示跑了1一個測試,0個錯誤1 examples, 0 failures

主要用途:

寫測試的用途通常比較有可能用在數學運算上,或是類似金流、銀行資訊,這種比較需要嚴謹的功能使用UnitTest會讓程式碼更有保證與穩定性。當然其他功能也是可以使用測試,養成先寫測試再寫程式的習慣。

--

--

Andy Kuan's Blog
Andy Kuan's Blog

Written by Andy Kuan's Blog

我是一個不斷喜歡學習科技的軟體工程師.

No responses yet