Rails 4 - 如何使用 rspec 通过自定义响应模拟异常?

Rails 4 - How to mock the exception with custom response using rspec?

提问人:Shruthi R 提问时间:8/26/2022 更新时间:8/26/2022 访问量:1322

问:

在 rails 4 中,我使用 rspec 编写测试用例。目前,我想模拟一个服务调用,该调用会引发异常并返回 required(custom) 输出。

例如:

allow(RestClient).to receive(:post).and_raise(User::APIError)

它的响应应该是这样的.and_return(error_response)

error_response等于一个可以是任何东西的对象。

请帮我写一个针对这种情况的规范。

ruby-on-rails ruby 异常 rspec rest-client

评论

0赞 spickermann 8/26/2022
“并返回自定义输出”是什么意思?您的意思是引发的异常分配了一条消息,并且您想测试该消息是否正确?或者它是否将错误消息输出到日志文件?
0赞 Shruthi R 8/26/2022
是的,引发的异常应该返回一条我想单独传递的消息。

答:

0赞 evilGenious 8/26/2022 #1

您可以尝试使用响应特定方法的实例 double。例:

api_error = instance_double(User::APIError, method_name: error_response)
allow(RestClient).to receive(:post).and_raise(api_error)

希望能有所帮助。

评论

0赞 Shruthi R 8/26/2022
出现类似User::APIError class does not implement the instance method: method_name
0赞 evilGenious 8/26/2022
这是因为没有实现该方法。您必须更改为尝试在实例上调用的任何方法。User::APIErrormethod_namemethod_nameUser::API
1赞 spickermann 8/26/2022 #2

我会这样嘲笑它:

allow(RestClient).to receive(:post).and_raise(User::APIError, 'custom error message')

请参阅有关模拟错误的文档

然后,您可以使用如下所示的特定消息测试是否引发了异常。

expect { method_calling_the_API }
  .to raise_error(an_instance_of(User::APIError)
  .and having_attributes(message: 'custom error message'))

有关错误匹配器,请参阅 RSpec 文档