gpt4 book ai didi

ruby-on-rails - Rspec 引发错误未按预期工作,需要正确的语法

转载 作者:行者123 更新时间:2023-12-04 15:36:26 24 4
gpt4 key购买 nike

我正在测试一个类引发错误

context 'with no office manager' do
let(:expected_response) do
{
error: "No office manager"
}
end
it 'returns an error' do
expect{ subject.run }.to raise_exception(an_instance_of(StandardError).and having_attributes(expected_response))
end
end

获取失败的测试响应:

expected Exception with an instance of StandardError and having attributes {:error => "No office manager"}, got #<StandardError: {:error=>"No office manager"}>

通过此测试的正确语法是什么?

最佳答案

我可以说常见将一个对象传递给一个异常而不是一个字符串来提示正在读取它的对象(或者也可能是 caller )。但是如果你想检查一下,你可以尝试将一个 block 传递给 raise_error并期待 block 参数 message方法等于 raise 的第二个参数:

RSpec.describe 'raise plus a non-string second argument' do
context 'with no office manager' do
let(:expected_response) do
{ error: 'No office manager' }
end

it 'returns an error' do
expect do
raise StandardError, expected_response
end.to raise_error(StandardError) { |error| expect(error.message).to eq expected_response.to_s }
end
end
end

通知,raise_errorraise_exception在功能上是可以互换的,因此,您可以使用在任何给定的上下文中对您来说都是最有意义的。

关于ruby-on-rails - Rspec 引发错误未按预期工作,需要正确的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59593280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com