代码之家  ›  专栏  ›  技术社区  ›  Petros Kyriakou

如何测试调用外部API的模型实例方法

  •  2
  • Petros Kyriakou  · 技术社区  · 8 年前

    我很难理解在下面的案例中要测试什么以及如何测试。

    我在地址模型上有以下实例方法

    validate :address, on: [:create, :update]
    
    def address
        check = CalendarEventLocationParsingWorker.new.perform("", self.structured, true )
        if check[:code] != 0
          errors.add(:base,"#{self.kind.capitalize} Address couldn't be analysed, please fill up as much fields as possible.")
        else
          self.lat = check[:coords]["lat"]
          self.lon = check[:coords]["lng"]
        end
      end
    

    基本上,它是一个调用create和update钩子的方法,并使用第三方API检查地址是否有效。我如何在不实际调用第三方api的情况下单独测试,而是模拟响应?

    我读过关于模拟和存根的文章,但我还不太明白。任何见解都是受欢迎的。使用Rspec,应该是匹配器和工厂女孩。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Slava.K    8 年前

    使用 webmock vcr 用于存根外部api响应的gems

    webmock的一个示例:

    stub_request(:get, "your external api url")
      .to_return(code: 0, coords: { lat: 1, lng: 2 })
    
    # test your address method here
    

    具有 录像机 您可以运行一次测试,它将对外部api进行实际调用,并将其响应记录到 .yml 文件,然后在所有后续测试中重用它。如果外部api响应发生更改,您可以直接删除 .yml 归档并记录新的示例响应。

        2
  •  0
  •   Sujan Adiga    8 年前

    你可以存根 perform 方法的任何实例上的 CalendarEventLocationParsingWorker 返回所需值

    语法:

    allow_any_instance_of(Class).to receive(:method).and_return(:return_value)
    

    前任:

    allow_any_instance_of(CalendarEventLocationParsingWorker).to receive(:perform).and_return({code: 0})
    

    参考: Allow a message on any instance of a class