如何测试该方法应该引发不同类型的异常?

时间:2012-03-28 03:12:50

标签: ruby exception rspec

我有以下方法:

  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

基于我对RSpec的有限理解,看起来测试引发这些不同类型的异常的方法是使用message expectations。这是你怎么做的?

1 个答案:

答案 0 :(得分:2)

它看起来像这样:

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

注意:拯救和重新引发不同的错误是代码味道。