提问人:Shruthi R 提问时间:8/26/2022 更新时间:8/26/2022 访问量:1322
Rails 4 - 如何使用 rspec 通过自定义响应模拟异常?
Rails 4 - How to mock the exception with custom response using rspec?
问:
在 rails 4 中,我使用 rspec 编写测试用例。目前,我想模拟一个服务调用,该调用会引发异常并返回 required(custom) 输出。
例如:
allow(RestClient).to receive(:post).and_raise(User::APIError)
它的响应应该是这样的.and_return(error_response)
error_response
等于一个可以是任何东西的对象。
请帮我写一个针对这种情况的规范。
答:
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::APIError
method_name
method_name
User::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'))
评论