我有一个方法,应该通过消息引发自定义错误。当我发现错误并引发自己的自定义错误时,它仍然在引发并打印原始错误的回溯。我只想要自定义错误和消息。下面的代码。
方法:
def load(configs)
begin
opts = {access_token: configs['token'],
api_endpoint: configs['endpoint'],
web_endpoint: configs['site'],
auto_paginate: configs['pagination']}
client = Octokit::Client.new(opts)
repos = client.org_repos(configs['org'])
repos.each do |r|
Project.create(name: r.name)
end
rescue Octokit::Unauthorized
raise GitConfigError, "boom"
end
#rescue Octokit::Unauthorized
end
class GitConfigError < StandardError
end
我的测试(失败):
context 'with incorrect git configs' do
before do
allow(loader).to receive(:load).and_raise Octokit::Unauthorized
end
it { expect{loader.load(configs)}.to raise_error(GitConfigError, "boom" ) }
end
测试输出:
GitProjectLoader#load with incorrect git configs should raise GitConfigError with "boom"
Failure/Error: it { expect{loader.load(configs)}.to raise_error(GitConfigError, "boom" ) }
expected GitConfigError with "boom", got #<Octokit::Unauthorized: Octokit::Unauthorized> with backtrace:
# ./spec/lib/git_project_loader_spec.rb:24:in `block (5 levels) in <top (required)>'
# ./spec/lib/git_project_loader_spec.rb:24:in `block (4 levels) in <top (required)>'
# ./spec/lib/git_project_loader_spec.rb:24:in `block (4 levels) in <top (required)>'
如果您打算测试Octokit::Unauthorized
错误的处理,那么在rescue
启动之前的任何地方引发错误。最好是在实际引发错误的地方。
像这样的东西,例如:
before do
allow(Octokit::Client).to receive(:new).and_raise(Octokit::Unauthorized)
end
然后:
expect{ loader.load(configs) }.to raise_error(GitConfigError, "boom" )
顺便说一句,我不建议将方法的所有行都封装在begin;rescue;end
结构中;您应该只将预期出现错误的行括起来。
您并没有按照自己的想法测试代码。你把它嘲弄了。
线路
allow(loader).to receive(:load).and_raise Octokit::Unauthorized
将loader
上的load
方法替换为仅引发命名错误的存根。
删除您的before
块,它应该会按预期测试您的代码。注意,正如所写的那样,它将通过Octokit发出真实的请求,除非你模拟它。