0
我有以下Ruby代碼:RSpec的嘲笑,`不能從一個示例組內name`
def report_deviation(departure)
deviation = departure.fetch('Dev')
trip = departure.fetch('Trip')
run_id = trip.fetch('RunId')
headsign = trip.fetch('InternetServiceDesc')
timestamp = Time.now.strftime '%l:%M %P'
FileUtils.mkdir 'log' unless File.directory? 'log'
File.open DAILY_LOG_FILE, 'a' do |file|
file.puts "#{timestamp}, #{name}: Run #{run_id} (#{headsign}), deviation #{deviation}"
end
end
由以下RSpec的代碼測試:
describe 'report_deviation' do
let(:departure) { double }
let(:trip) { double }
let(:file) { double }
it 'appends to a log file with the correct entry format' do
expect(departure).to receive(:fetch).with('Trip').and_return trip
expect(departure).to receive(:fetch).with('Dev').and_return 'DEVIATION'
expect(trip).to receive(:fetch).with('RunId')
.and_return 'RUN'
expect(trip).to receive(:fetch).with('InternetServiceDesc')
.and_return 'HEADSIGN'
stub_const 'DeviationValidator::DAILY_LOG_FILE', :log_file
expect(File).to receive(:open).with(:log_file, 'a').and_yield file
timestamp = '12:00 pm: Run RUN (HEADSIGN), deviation DEVIATION'
expect(file).to receive(:puts).with timestamp
Timecop.freeze(Time.new 2017, 7, 31, 12) { report_deviation(departure) }
end
end
但是當我運行我接收失敗消息:
`name` is not available from within an example (e.g. an `it` block) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). It is only available on an example group (e.g. a `describe` or `context` block).
字name
沒有在任何地方這裏寫的,如果我刪除了最後測試線(調用實際代碼)我得到了測試失敗,我期望對於不滿意的異常。我通常會將我的代碼燒寫到導致錯誤的部分,但我不知道是什麼導致了錯誤。
爲什麼它的價值,在回溯中提到的具體行號是 File.open
塊 - 但我不明白爲什麼會導致失敗。我已經設置了測試雙打,這些對象沒有什麼特別 - File
收到open
並且產生file
,其唯一的工作就是聽我收到我想要的字符串puts
。那麼,什麼樣的代碼調用什麼是一個關鍵字RSpec方法name
?
唉錯過了,謝謝!這就是當我快速進行方法抽象時發生的事情...... – dfaulken