一、為什么需要測試:
測試對于程序來說,不是必不必要的問題,而是怎么測的問題。就算不寫測試,你一樣在人肉測試。只不過人肉測試效率太低,出錯率也高,對于中等和以上規模的程序,需要寫測試來代替人肉測試,以減輕工作強度罷了。
功能和代碼不斷的擴充,不斷重構和優化,這個過程中,沒有好的測試,基本就掉入修bug泥潭了。有話說改一個bug帶來3個bug,自動測試一定程度上可以減輕這個狀況。總之,邏輯簡單,或者寫完沒有更改的必要,類似這種代碼人肉測測也無可厚非,邏輯稍微復雜的,以后更改的可能性存在的, 那么自動測試毫無疑問是必要的。
二、安裝
在Gemfile配置文件中,配置如下信息
group :test do
gem 'rspec-rails', '~> 3.7'
end
執行bundle install
來安裝這個gem,此gem依賴gem rspec
,所以不用單獨安裝rspec。
然后執行 rails generate rspec:install
生成rspec相關文件,會生成以下三個文件
.rspec
spec/spec_helper.rb
spec/rails_helper.rb
運行rspec命令執行測試
bundle exec rspec
或 bundle exec rake spec
此命令會執行spec文件夾下的所有以_spec.rb
結尾的文件。
三、示例
下面是要測試的model文件
# models/app/user.rb
class App::User < ApplicationRecord
def is_employee?
self.app_user_type.to_i == 21
end
end
我們要測試user.rb文件下的實例方法is_employee?
,這個方法可能返回兩個值true
和false
,所以我們的測試要分兩種情況
#spec/models/app/user_spec.rb
require "rails_helper"
RSpec.describe App::User, :type => :model do
describe '#is_employee?' do
context "when app_user is employee" do
it "should respond with true" do
app_user = App::User.create!(true_name: '王先生', mobile: '13700000000', app_user_type: 1)
expect(app_user.is_employee?).to eq(false)
end
end
context "when app_user is not employee" do
it "should respond with false" do
app_user = App::User.create!(true_name: '王先生', mobile: '13700000000', app_user_type: 21)
expect(app_user.is_employee?).to eq(true)
end
end
end
end
(注釋:通常,我們使用describe來描述方法。遵循ruby注釋規范,在方法名前使用點號‘.’或‘::’表示測試的是類方法,用“#”表示測試的是實例方法)
然后在控制臺執行bundle exec rspec
(或者只執行某個文件rspec spec/models/app/user_spec.rb
),在控制臺會看到下面的內容:
如果失敗了是什么情況呢?我們把第一段的eq(false)
改成eq(true)
看一下運行結果:
四、數據準備方法let
如果再添加user的其他實例方法,我需要在新的測試例子中再創建一個app_user
實例,再測試的例子越來越多時會發現數據準備占了大部分的代碼量。
# 這一段:
let(:app_user) { App::User.new }
# 基本上和這一段完全等同
def app_user
@app_user ||= App::User.new
end
這時我們就需要用到let方法,如下:
#spec/models/app/user_spec.rb
require "rails_helper"
RSpec.describe App::User, :type => :model do
describe '#is_employee?' do
let(:app_user) {App::User.create!(true_name: '王先生', mobile: '13700000000', app_user_type: 1)}
let (:employee_user) {App::User.create!(true_name: '王先生', mobile: '13700000000', app_user_type: 21)}
context "when app_user is employee"
...
context "when app_user is not employee"
...
end
end
其實還有一個方法before,可以這樣寫(但我們通常不用before)
describe '#is_employee?' do
before { @app_user = App::User.create :app_user_type, :mobile, :true_name}
it "should respond with false" do
expect(@app_user.is_employee?).to eq(true)
end
end
當需要給一個變量賦值時,使用 let
而不是before
來創建這個實例變量。let
采用了 lazy load 的機制,只有在第一次用到的時候才會加載,然后就被緩存,直到測試結束。
而before(:each)
會自動初始化變量。如果其中的某一個測試用力不需要這些變量,依然需要初始化,如初始化變量需要很多時間,對這個測試的初始化會浪費多余的時間和資源.
五、factory_bot
一個讓數據準備更方便的工具
rails下安裝:gem "factory_bot_rails"
配置,在config/environments/test.rb
下配置如下內容:
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
在spec下創建一個factories文件夾,在這個文件夾下做FactoryBot數據相關的配置
比如上面提到的App::User的配置:
FactoryBot.define do
# employee賬號
factory :employee_user, class: 'App::User' do
id 10360
app_user_type 21
true_name '吳先生'
mobile 13700000000
end
# 非employee賬號
factory :app_user, class: 'App::User' do
id 10361
app_user_type 3
true_name '王先生'
mobile 13700000000
end
end
然后我們的測試就可以這樣寫:
describe '#is_employee?' do
let (:app_user) {build(:app_user)}
let (:employee_user) {build(:employee_user)}
context "when app_user is employee" do
it "should respond with true" do
expect(app_user.is_employee?).to eq(false)
end
end
context "when app_user is not employee" do
it "should respond with false" do
expect(employee_user.is_employee?).to eq(true)
end
end
end
在FactoryBot定義時我們可以只定義一個app_user,employee_user可以這樣生成:
let(:app_user) { build(:app_user) }
let(:employee_user) { build(:app_user, app_user_type: 3) }
build相當于App::User.new, FactoryBot還有create等其他方法,具體方法參考https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md
六、模擬方法--mock
# models/app/user.rb
def type_name
self.is_employee? ? '高級賬號' : '普通賬號'
end
如果self.is_employee?
判斷很多,在測試type_name
方法時我們不用過多的為is_employee?
準備數據,我們應該只關注type_name
方法的測試,這時候我們只需要這樣:
app_user.should_receive(:is_employee?).and_return(true)
expect(app_user.type_name).to eq('高級賬號')
通過mock方法,我們可以模擬某些值或方法,在上面的方法中,我們模擬方法is_employee?
始終返回true。
FactoryGirl模擬真實的字段,mock可以模擬模型不存在的字段,mock可以用來虛擬比較復雜的屬性或方法。
七、rspec斷言
rspec 提供豐富多樣的斷言形式,滿足我們的大部分需求,下面是其中一部分語法:
1、equal:
expect(actual).to be(expected) # passes if actual.equal?(expected)
expect(actual).to equal(expected) # passes if actual.equal?(expected)
expect(actual).not_to eq(expected)
2、比較:
expect(actual).to be > expected
expect(actual).to be >= expected
expect(actual).to be <= expected
expect(actual).to be < expected
expect(actual).to be_within(delta).of(expected)
3、正則表示式:
expect(actual).to match(/expression/)
Note: The new expect syntax no longer supports the=~ matcher.
4、Types/classes:
expect(actual).to be_an_instance_of(expected) # passes if actual.class == expected
expect(actual).to be_a(expected) # passes if actual.is_a?(expected)
expect(actual).to be_an(expected) # an alias for be_a
expect(actual).to be_a_kind_of(expected) # another alias
5、真假匹配:
expect(actual).to be_truthy # passes if actual is truthy (not nil or false)
expect(actual).to be true # passes if actual == true
expect(actual).to be_falsy # passes if actual is falsy (nil or false)
expect(actual).to be false # passes if actual == false
expect(actual).to be_nil # passes if actual is nil
expect(actual).to_not be_nil # passes if actual is not nil
6、報錯部分:
expect { ... }.to raise_error
expect { ... }.to raise_error(ErrorClass)
expect { ... }.to raise_error("message")
expect { ... }.to raise_error(ErrorClass, "message")
7、throws:
expect { ... }.to throw_symbol
expect { ... }.to throw_symbol(:symbol)
expect { ... }.to throw_symbol(:symbol, 'value')
8、謂詞匹配器:
expect(actual).to be_xxx # passes if actual.xxx?expect(actual).to have_xxx(:arg) # passes if actual.has_xxx?(:arg)
9、集合:
expect(actual).to include(expected)
expect(actual).to start_with(expected)
expect(actual).to end_with(expected)
expect(actual).to contain_exactly(individual, items)# …which is the same as:expect(actual).to match_array( expected_array )
例子:
expect([1, 2, 3]).to include(1)
expect([1, 2, 3]).to include(1, 2)
expect([1, 2, 3]).to start_with(1)
expect([1, 2, 3]).to start_with(1, 2)
expect([1, 2, 3]).to end_with(3)
expect([1, 2, 3]).to end_with(2, 3)
expect({:a => 'b'}).to include(:a => 'b')
expect("this string").to include("is str")
expect("this string").to start_with("this")
expect("this string").to end_with("ring")
expect([1, 2, 3]).to contain_exactly(2, 3, 1)
expect([1, 2, 3]).to match_array([3, 2, 1])
八、測試報告
執行下面的命令生成測試報錯,生成的文件在項目根目錄下
rspec --format html --out rspec_test.html
下面是測試報告的頁面:
九、結束語
看看這篇文章,理解為什么需要測試,對自己的代碼負責!
https://chloerei.com/2015/10/26/testing-guide/
人非圣賢孰能無過,不同于 C/C++這類編譯型語言,ruby作為解釋型語言,有些語法性的錯誤有時較難發現,測試能為我們規避不少這類問題!