Rspec 引发错误未按预期工作,需要正确的语法
Rspec raise error not working as expected, need correct syntax
我正在测试 class 引发错误
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"}>
通过此测试的正确语法是什么?
我可以说 common 将对象传递给异常而不是字符串来提示正在读取它的对象(或者 caller
).但是如果你想检查一下,你可以尝试将一个块传递给 raise_error
并期望块参数 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_error
和 raise_exception
在功能上可以互换,因此,您可以使用
在任何给定的上下文中对您来说都是最有意义的。
Ruby 中的异常有 #message
method/attribute,但没有 #error
。所以你需要改变
let(:expected_response) do
{
error: "No office manager"
}
end
至
let(:expected_response) do
{
message: "No office manager"
}
end
我正在测试 class 引发错误
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"}>
通过此测试的正确语法是什么?
我可以说 common 将对象传递给异常而不是字符串来提示正在读取它的对象(或者 caller
).但是如果你想检查一下,你可以尝试将一个块传递给 raise_error
并期望块参数 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_error
和 raise_exception
在功能上可以互换,因此,您可以使用
在任何给定的上下文中对您来说都是最有意义的。
Ruby 中的异常有 #message
method/attribute,但没有 #error
。所以你需要改变
let(:expected_response) do
{
error: "No office manager"
}
end
至
let(:expected_response) do
{
message: "No office manager"
}
end