[英]Rspec for begin ... rescue block in rails
我正在編寫一個測試,它應該驗證當 object 創建保存時,確實捕獲了異常。
begin
object.create!(item)
rescue => exception
exception.message
end
rspec
expect{ exception.message }.to eq("Validation failed: Item name can't be blank")
output 我得到:
Failure/Error: expect{ exception.message }.to eq("Validation failed: Item name can't be blank")
You must pass an argument rather than a block to `expect` to use the provided matcher (eq "Validation failed: Item name can't be blank"), or the matcher must implement `supports_block_expectations?`.
誰能幫我嗎?
你不能這樣測試你的代碼,因為exception
變量只存在於rescue
塊中。 相反,您需要調用要測試的方法並添加對它應該返回的內容的期望。
您的示例實際上沒有可以調用的方法。 我想你的方法實際上是這樣的:
def do_stuff_with(object, item)
begin
object.create!(item)
rescue => exception
exception.message
end
end
那么你應該能夠有這樣的期望:
expect(do_stuff_with(object, item)).to eq(
"Validation failed: Item name can't be blank"
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.