假設我有以下代碼。
class Answer
enum type: %i[text checkbox image]
def round_type
case answer.type
when text, checkbox
:text
when image
:multimedia
else
raise 'Unknown type'
end
end
end
require 'rails_helper'
RSpec.describe Answer, type: :model do
describe '#round_type' do
context 'when type is text' do
it 'returns text' do
# omitted
end
end
context 'when type is checkbox' do
it 'returns text' do
end
end
context 'when type is image' do
it 'returns multimedia' do
end
end
end
end
然后我將視頻型別添加到列舉中。我希望該方法在型別為視頻時回傳多媒體。
但 round_type 方法和測驗代碼不支持視頻型別。因此,當我在生產中遇到錯誤時,我最終會意識到這一點。
我想知道在錯誤發生之前我必須更改方法。
所以,這是我的問題:當我必須更改 rspec 中的方法時,如何檢測時間?
uj5u.com熱心網友回復:
如果我的理解正確,你必須讓你的規范更有活力,你還必須測驗這個else陳述句:
class Answer
enum type: %i[text checkbox image]
def round_type
case type
when 'text', 'checkbox'
:text
when 'image'
:multimedia
else
raise 'Unknown type'
end
end
end
RSpec.describe Answer, type: :model do
describe '#round_type' do
it 'raises error for unknown type' do
# empty `type` is an unknown type in this situation
expect { Answer.new.round_type }.to raise_error
end
it 'does not raise error for available types' do
# NOTE: loop through all types and check that `round_type` method
# recognizes each one.
Answer.types.each_key do |key|
expect { Answer.new(type: key).round_type }.to_not raise_error
end
end
end
end
下次您添加新方法type并忘記更新round_type方法時,最后一個規范將失敗。
https://relishapp.com/rspec/rspec-expectations/v/3-11/docs/built-in-matchers/raise-error-matcher
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/478519.html
上一篇:在Ruby中決議時間
