一、為什么需要測(cè)試:
測(cè)試對(duì)于程序來(lái)說(shuō)堰酿,不是必不必要的問題疾宏,而是怎么測(cè)的問題。就算不寫測(cè)試触创,你一樣在人肉測(cè)試坎藐。只不過人肉測(cè)試效率太低,出錯(cuò)率也高哼绑,對(duì)于中等和以上規(guī)模的程序岩馍,需要寫測(cè)試來(lái)代替人肉測(cè)試,以減輕工作強(qiáng)度罷了抖韩。
功能和代碼不斷的擴(kuò)充蛀恩,不斷重構(gòu)和優(yōu)化,這個(gè)過程中茂浮,沒有好的測(cè)試双谆,基本就掉入修bug泥潭了壳咕。有話說(shuō)改一個(gè)bug帶來(lái)3個(gè)bug,自動(dòng)測(cè)試一定程度上可以減輕這個(gè)狀況顽馋〈丫總之,邏輯簡(jiǎn)單趣避,或者寫完沒有更改的必要,類似這種代碼人肉測(cè)測(cè)也無(wú)可厚非新翎,邏輯稍微復(fù)雜的程帕,以后更改的可能性存在的, 那么自動(dòng)測(cè)試毫無(wú)疑問是必要的。
二地啰、安裝
在Gemfile配置文件中愁拭,配置如下信息
group :test do
gem 'rspec-rails', '~> 3.7'
end
執(zhí)行bundle install
來(lái)安裝這個(gè)gem,此gem依賴gem rspec
亏吝,所以不用單獨(dú)安裝rspec岭埠。
然后執(zhí)行 rails generate rspec:install
生成rspec相關(guān)文件,會(huì)生成以下三個(gè)文件
.rspec
spec/spec_helper.rb
spec/rails_helper.rb
運(yùn)行rspec命令執(zhí)行測(cè)試
bundle exec rspec
或 bundle exec rake spec
此命令會(huì)執(zhí)行spec文件夾下的所有以_spec.rb
結(jié)尾的文件蔚鸥。
三惜论、示例
下面是要測(cè)試的model文件
# models/app/user.rb
class App::User < ApplicationRecord
def is_employee?
self.app_user_type.to_i == 21
end
end
我們要測(cè)試user.rb文件下的實(shí)例方法is_employee?
,這個(gè)方法可能返回兩個(gè)值true
和false
止喷,所以我們的測(cè)試要分兩種情況
#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來(lái)描述方法。遵循ruby注釋規(guī)范弹谁,在方法名前使用點(diǎn)號(hào)‘.’或‘::’表示測(cè)試的是類方法乾巧,用“#”表示測(cè)試的是實(shí)例方法)
然后在控制臺(tái)執(zhí)行bundle exec rspec
(或者只執(zhí)行某個(gè)文件rspec spec/models/app/user_spec.rb
),在控制臺(tái)會(huì)看到下面的內(nèi)容:
如果失敗了是什么情況呢沟于?我們把第一段的eq(false)
改成eq(true)
看一下運(yùn)行結(jié)果:
四、數(shù)據(jù)準(zhǔn)備方法let
如果再添加user的其他實(shí)例方法植康,我需要在新的測(cè)試?yán)又性賱?chuàng)建一個(gè)app_user
實(shí)例旷太,再測(cè)試的例子越來(lái)越多時(shí)會(huì)發(fā)現(xiàn)數(shù)據(jù)準(zhǔn)備占了大部分的代碼量。
# 這一段:
let(:app_user) { App::User.new }
# 基本上和這一段完全等同
def app_user
@app_user ||= App::User.new
end
這時(shí)我們就需要用到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
其實(shí)還有一個(gè)方法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
當(dāng)需要給一個(gè)變量賦值時(shí),使用 let
而不是before
來(lái)創(chuàng)建這個(gè)實(shí)例變量榄攀。let
采用了 lazy load 的機(jī)制嗜傅,只有在第一次用到的時(shí)候才會(huì)加載,然后就被緩存檩赢,直到測(cè)試結(jié)束吕嘀。
而before(:each)
會(huì)自動(dòng)初始化變量违寞。如果其中的某一個(gè)測(cè)試用力不需要這些變量,依然需要初始化偶房,如初始化變量需要很多時(shí)間趁曼,對(duì)這個(gè)測(cè)試的初始化會(huì)浪費(fèi)多余的時(shí)間和資源.
五、factory_bot
一個(gè)讓數(shù)據(jù)準(zhǔn)備更方便的工具
rails下安裝:gem "factory_bot_rails"
配置棕洋,在config/environments/test.rb
下配置如下內(nèi)容:
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
在spec下創(chuàng)建一個(gè)factories文件夾挡闰,在這個(gè)文件夾下做FactoryBot數(shù)據(jù)相關(guān)的配置
比如上面提到的App::User的配置:
FactoryBot.define do
# employee賬號(hào)
factory :employee_user, class: 'App::User' do
id 10360
app_user_type 21
true_name '吳先生'
mobile 13700000000
end
# 非employee賬號(hào)
factory :app_user, class: 'App::User' do
id 10361
app_user_type 3
true_name '王先生'
mobile 13700000000
end
end
然后我們的測(cè)試就可以這樣寫:
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定義時(shí)我們可以只定義一個(gè)app_user,employee_user可以這樣生成:
let(:app_user) { build(:app_user) }
let(:employee_user) { build(:app_user, app_user_type: 3) }
build相當(dāng)于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? ? '高級(jí)賬號(hào)' : '普通賬號(hào)'
end
如果self.is_employee?
判斷很多,在測(cè)試type_name
方法時(shí)我們不用過多的為is_employee?
準(zhǔn)備數(shù)據(jù)愧捕,我們應(yīng)該只關(guān)注type_name
方法的測(cè)試奢驯,這時(shí)候我們只需要這樣:
app_user.should_receive(:is_employee?).and_return(true)
expect(app_user.type_name).to eq('高級(jí)賬號(hào)')
通過mock方法,我們可以模擬某些值或方法次绘,在上面的方法中瘪阁,我們模擬方法is_employee?
始終返回true。
FactoryGirl模擬真實(shí)的字段邮偎,mock可以模擬模型不存在的字段管跺,mock可以用來(lái)虛擬比較復(fù)雜的屬性或方法。
七禾进、rspec斷言
rspec 提供豐富多樣的斷言形式伙菜,滿足我們的大部分需求,下面是其中一部分語(yǔ)法:
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、報(bào)錯(cuò)部分:
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])
八勃救、測(cè)試報(bào)告
執(zhí)行下面的命令生成測(cè)試報(bào)錯(cuò)碍讨,生成的文件在項(xiàng)目根目錄下
rspec --format html --out rspec_test.html
下面是測(cè)試報(bào)告的頁(yè)面:
九、結(jié)束語(yǔ)
看看這篇文章蒙秒,理解為什么需要測(cè)試勃黍,對(duì)自己的代碼負(fù)責(zé)!
https://chloerei.com/2015/10/26/testing-guide/
人非圣賢孰能無(wú)過晕讲,不同于 C/C++這類編譯型語(yǔ)言覆获,ruby作為解釋型語(yǔ)言马澈,有些語(yǔ)法性的錯(cuò)誤有時(shí)較難發(fā)現(xiàn),測(cè)試能為我們規(guī)避不少這類問題弄息!