2017-06-16 18 views
0

我想對從Rails模型中輸出格式化Json的Ruby服務進行基準測試。Ruby基準測試:在腳本中嘲諷外部API

#!/usr/bin/env/rails r 

require 'benchmark' 

sample_project = Project.last 
formatter = Formatter.new(sample_project) 

Benchmark.bm(10) do |x| 
    x.report('creation:') { Formatter.new(sample_project) } 
    x.report('output:') { formatter.output } 
end 

此腳本失敗,因爲formatter.output調用外部API並不能得到答案。

沒有這個調用,我的代碼很慢。我的第一個反應是試圖存留這個電話,但我無法成功設置它。而且我不知道這是否是建立我的基準測試的最佳方式。

這裏採用的最佳策略是什麼?

+0

爲什麼不使用像webmock這樣的庫? – BKSpurgeon

+0

我正在使用自制的gem與該API交談,對於我來說stub一種方法,rspec風格會更容易。 – Ruff9

回答

0

末梢一些方法最簡單的方法是重新打開你的類(這使得externall API調用),並覆蓋所需的方法

例如在加載文件之後並在運行基準測試之前加載它

Formatter.class_eval do 
    def make_api_call 
    {foo: 'bar'} # some stubbed values 
    end 
end