【问题标题】:How to test that method should raise different types of exceptions?如何测试该方法应该引发不同类型的异常?
【发布时间】:2012-04-11 15:22:33
【问题描述】:

我有以下方法:

  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。你会这样处理它吗?

【问题讨论】:

    标签: ruby exception rspec


    【解决方案1】:

    看起来像这样:

    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多