[英]How do I test that a RuntimeError is using string interpolation correctly in Ruby?
我有一個方法可以在數據庫中記錄對特定記錄的更改,但是首先,它會在進一步檢查之前檢查類別類型的有效性。 如果返回false,則會引發錯誤。
class UpgradePackageRecorder
CATEGORIES = [ an array of categories here ... ]
def initialize(category)
@category = category
end
def record_change
unless valid_category?
raise "#{category} is not a recognized category"
end
other_methods
end
private
def valid_category?
CATEGORIES.include?(category)
end
end
我開始為此編寫rspec測試,以驗證是否正確引發了錯誤。 這是測試用例:
RSpec.describe UpgradePackageRecorder do
describe '#record_change' do
context 'the package type is invalid' do
it 'raises an error' do
recorder = UpgradePackageRecorder.new('Bronze')
expect { recorder.record_change }.to raise_error(RuntimeError, /bronze is not a recognized category/)
end
end
end
end
當我運行測試時,出現以下錯誤:
Failure/Error: raise "#{category} is not a recognized category"
RuntimeError:
bronze is not a recognized category
為什么字符串插值會這樣顯示? 我也嘗試過嘗試category + ' is not a recognized category
但這不能解決問題。
為了使這一點更加混亂,我取出了字符串插值,仍然看到了這個問題:
Failure/Error: raise "Unrecognized category"
RuntimeError:
Unrecognized category
我想到了!
最終對我有用的語法是:
it 'raises an error' do
expect do
UpgradePackageRecorder.new(
'Bronze'
).record_change
end.to raise_error(
RuntimeError, /bronze is not a recognized category/
)
end
另外,在刪除的相同it
塊中,我還有另一個expect
。 它正在驗證record_change
方法是否繼續創建某個對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.