NuLLByt3
NuLLByt3

Reputation: 109

Ruby: how to test against an exception

I'm new to Ruby, I would like to write a spec against logger expection using allow. Please help, thank you.

Current spec

    it 'raises exception fetching auditables' do
  allow(NightLiaison::HttpConnection.open).to receive(:get).and_raise(StandardError)
  expect { described_class.fetch_auditables }.to raise_error('Fetching auditables raised an exception')
end

end

Method:

    def self.fetch_auditables
    HttpConnection.open.get AppConfig.api.nightliaison.fetch_auditables
     rescue => e
        LOGGER.error('Fetching auditables raised an exception', exception: e)
        Faraday::Response.new
      end

Error Message:

got #<WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled. Unregistered request: GET h... => 200, :body => "", :headers => {})

Upvotes: 0

Views: 652

Answers (2)

LucasM
LucasM

Reputation: 373

Try:

allow(NightLiaison::HttpConnection).to receive_message_chain(:open, :get) { raise StandardError }

Upvotes: 1

Taryn East
Taryn East

Reputation: 27747

Looks like it fails when it tries open - if you mock that too, it could work. Try something like:

it 'raises exception fetching auditables' do
  open_mock = double
  allow(open_mock).to receive(:get).and_raise(StandardError)
  allow(NightLiaison::HttpConnection).to receive(:open).and_return(open_mock)
  expect { described_class.fetch_auditables }.to raise_error('Fetching auditables raised an exception')
end

Upvotes: 1

Related Questions