简体   繁体   中英

Ruby script raising unexpected backtrace

I have a method that should raise a custom error with a message. When I catch the error and raise my own custom error, it is still raising and printing the backtrace of the original error. I just want the custom error and message. Code below.

Method:

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

My test (which is failling):

 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

Test Output:

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

If you intend to test the handling of the Octokit::Unauthorized error, then raise the error anywhere before the rescue kicks in. Preferably, someplace where it would actually be raised.

Something like this, for example:

before do
  allow(Octokit::Client).to receive(:new).and_raise(Octokit::Unauthorized)
end

And then:

expect{ loader.load(configs) }.to raise_error(GitConfigError, "boom" )

As a side note, I would discourage enclosing all lines of your method in a begin;rescue;end structure; you should enclose only the lines from which you are expecting errors.

You are not testing your code as you think. You have mocked it out.

The line

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

replaces the load method on loader with a stub which just raises the named error.

Remove your before block, and it should test your code as intended. Note as written it will make a real request via Octokit, unless you mock that out instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM