gpt4 book ai didi

ruby-on-rails - 如何在 RSpec 中 stub 错误异常?

转载 作者:行者123 更新时间:2023-12-05 03:00:29 26 4
gpt4 key购买 nike

当它进入异常部分以遵循“.get”方法时,我不确定如何进行测试:

/api/reddit_client.rb:

module Api
class RedditClient

def self.get(path, access_token)
begin
response = RestClient.get(
path,
{ :Authorization => "Bearer #{access_token}" }
)

json_parse(response)
rescue RestClient::ExceptionWithResponse => e
logger.error "%%% Something went wrong in request post"
logger.error "%%% It fails with error: #{e.http_code}"
logger.error "%%% And with message: #{e.message}"

{ "message" => e.message, "error" => e.http_code }
end
end

...
...
...

private

def json_parse(response)
JSON.parse(response.body)
end
end
end

我希望它测试它是否引发“RestClient::ExceptionWithResponse”,为此我执行了以下操作:

/api/reddit_client_spec.rb:

require 'rails_helper'

RSpec.describe Api::RedditClient do
let(:path) { 'https://www.somerandomapi.com' }
let(:access_token) { 'f00TOk3N' }

describe '.get' do
subject { described_class.get(path, access_token)}

context 'when not authorized' do
before do
allow(described_class)
.to receive(:get)
.and_raise(RestClient::ExceptionWithResponse)
end

it 'returns hash with error infos' do
expect{ subject }.to raise_error(RestClient::ExceptionWithResponse)
end
end
end
end

欺骗我的是,我还想测试 Rails.logger.error 是否也被调用了 3 次,并检查我的哈希错误返回值。如何测试这种情况?

最佳答案

为了检查 Rails logger 是否被调用了 3 次不同的消息,您可以结合使用 receiveordered 方法。

还使用 RestClient 而不是 Api::RedditClient 来执行该方法并捕获异常。

你的代码将是这样的:

 context 'when not authorized' do
before do
allow(RestClient) # <- Note that you should use RestClient instead of Api::RedditClient
.to receive(:get)
.and_raise(RestClient::ExceptionWithResponse)
end

it 'should raise error' do
expect(Rails.logger).to receive(:error).with("%%% Something went wrong in request post").ordered
expect(Rails.logger).to receive(:error).with(""%%% It fails with error: 401"").ordered
expect(Rails.logger).to receive(:error).with("%%% And with message: Exception Message").ordered

expect{ subject }.to raise_error(RestClient::ExceptionWithResponse)
end
end

要检查返回响应,您可以在测试中挽救异常并检查返回类型

it 'returns hash with error infos' do
expect{ subject rescue nil}.to include({ "message" => "Exception Message", "error" => 401 })
end

希望对你有帮助

关于ruby-on-rails - 如何在 RSpec 中 stub 错误异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56759415/

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