看隔壁關於 ORM 的討論說 Ruby/Rails 的長處都被其他語言學走了,但我覺得至少 RSpec 在 JS 世界還沒有替代。以下是一個用 RSpec 寫測試的例子:
require 'rspec'
require 'matrix'
RSpec.describe 'numbers' do
# 描述加法的性質
shared_examples 'addition' do
# 加法滿足交換律
# a 和 b 會在實際的 context 裏注入
it 'has commutativity' do
expect(a + b).to eq(b + a)
end
end
context 'for number' do
# 令 a 和 b 為兩個隨機數,並調用加法的測試用例
let(:a) { Random.rand }
let(:b) { Random.rand }
it_behaves_like 'addition'
end
context 'for vector' do
# a 和 b 可以是向量,也滿足加法的性質
let(:a) { Vector[Random.rand, Random.rand] }
let(:b) { Vector[Random.rand, Random.rand] }
it_behaves_like 'addition'
end
end
如果要用 js 寫,至少所有的 a 和 b 都要換成類似context.a context.b,因為 ruby 有 self ,而 js 只有詞法作用域,這導致 js 的 dsl 表達力很受限。
另外在 ruby 裏也可以很輕易做 mock ,例如這個例子修改了Date.today來返回我們測試用的日期:
require 'rspec'
require 'date'
RSpec.describe 'Date' do
# 選定一個測試用的日期,一般來說實際會使用隨機的
let(:date) { Date.parse('1970-01-01') }
before do
# Date.today 本身是標準庫定義好的,但我們可以覆寫它來返回我們的日期
allow(Date).to receive(:today).and_return(date)
end
describe '.today' do
it 'is the mocked date' do
# Date.today 現在會是我們 mock 的日期 1970-01-01
expect(Date.today).to eq(date)
end
end
end
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.