You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为使用HTTParty的距离计算方法编写对应的RSpec测试

要完成这个测试,你需要先处理方法的变量作用域问题,再通过Mock第三方接口请求的方式编写用例,避免测试依赖外部网络和接口可用性,具体实现如下:

1. 修正原方法的变量作用域问题

你当前方法中定义的distance是局部变量,方法执行完成后就会被销毁,外部无法访问到这个值。如果你需要将解析后的距离赋值给实例变量供其他逻辑使用,需要修改为实例变量:

require 'httparty'
def distance_calculation
    url = "https://api.distancematrix.ai/maps/api/distancematrix/json?origins=#{@departure}&destinations=#{@destination}&key=lugtcyuuvliub;o;o"
    response = HTTParty.get(url)
    # 改为实例变量,外部可以访问
    @distance = response.parsed_response["rows"].first["elements"].first["distance"]["text"]
end

如果你只是需要方法返回距离值不需要额外赋值,那局部变量不用改,Ruby会默认返回方法最后一行的执行结果。

2. 编写RSpec测试用例

测试核心思路是Mock HTTParty的请求,返回固定的模拟接口响应,避免真实调用第三方接口,再验证赋值/返回结果符合预期:

describe "#distance_calculation" do
  # 预设测试用的出发地和目的地值
  let(:test_departure) { "北京" }
  let(:test_destination) { "上海" }
  # 模拟接口返回的结构,和你提到的实际返回字段对齐
  let(:mock_response) do
    {
      "destination_addresses" => ["上海市"],
      "origin_addresses" => ["北京市"],
      "rows" => [
        {
          "elements" => [
            {
              "distance" => { "text" => "1200公里", "value" => 1200000 },
              "duration" => { "text" => "12小时", "value" => 43200 }
            }
          ]
        }
      ]
    }
  end

  before do
    # 给实例赋值出发地和目的地
    @departure = test_departure
    @destination = test_destination
    # Stub HTTParty.get方法,返回固定的模拟响应
    allow(HTTParty).to receive(:get).with(include(test_departure, test_destination)).and_return(double(parsed_response: mock_response))
  end

  context "距离计算逻辑验证" do
    it "正确解析接口返回的距离值并赋值给@distance实例变量" do
      # 调用目标方法
      distance_calculation
      # 验证实例变量赋值符合预期
      expect(@distance).to eq("1200公里")
    end

    # 如果你是用方法返回值的方式,用下面的用例即可
    it "正确返回接口解析的公里格式距离" do
      expect(distance_calculation).to eq("1200公里")
    end
  end
end

如果需要额外验证接口返回的其他字段(比如origin_addresses、destination_addresses),可以在方法中添加对应的实例变量赋值,再在测试中增加对应的expect校验即可。

内容的提问来源于stack exchange,提问作者WWW1981

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:36:03