Ruby 脚本引发意外回溯

Ruby script raising unexpected backtrace

我有一个方法可以通过消息引发自定义错误。当我捕获错误并引发我自己的自定义错误时,它仍在引发并打印原始错误的回溯。我只想要自定义错误和消息。下面的代码。

方法:

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)>'

您没有按照您的想法测试您的代码。你嘲笑了它。

allow(loader).to receive(:load).and_raise Octokit::Unauthorized

loader 上的 load 方法替换为一个只引发命名错误的存根。

删除您的 before 块,它应该按预期测试您的代码。请注意,如所写,它将通过 Octokit 发出 real 请求,除非您改为模拟它。

如果您打算测试 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 结构中;您应该只包含您预计会出现错误的行。