keruilin
keruilin

Reputation: 17512

How to test that method should raise different types of exceptions?

I have the following method:

  def call_http_service(url, url_params)
    begin
      conn = create_connection(url)
      resp = get_response(conn, url_params)
      raise_if_http_status_error(resp)
      xml_resp = parse_xml(resp)
      raise_if_client_status_error(xml_resp)

      return xml_resp
    rescue ClientError => e
      raise ClientError, "Error interacting with feed at #{url}: #{e.message}"
    rescue Faraday::Error::ClientError => e
      raise ClientError, "Error interacting with feed at #{url}: #{e.message}"
    rescue Nokogiri::XML::SyntaxError => e
      raise ClientParseError, "Error parsing response from #{url}: #{e.message}"
    rescue => e
      raise e
    end
  end

Based on my limited understanding of RSpec, it looks like the way to test that these different types of Exceptions are raised is to use message expectations. Is that how you would approach it?

Upvotes: 0

Views: 575

Answers (1)

Austin
Austin

Reputation: 3890

It would look something like this:

it "raises ClientError when the HTTP request raises ClientError"
  # stub the http request here to raise the error
  expect do
    subject.call_http_service 'http://example.com'
  end.to raise_error(ClientError)
end

Note: Rescuing and reraising a different error is code smell.

Upvotes: 2

Related Questions