【发布时间】:2019-11-07 14:37:04
【问题描述】:
当它进入异常部分以遵循“.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 次,并检查我的哈希错误返回。如何测试这种情况?
【问题讨论】:
标签: ruby-on-rails rspec stub