【问题标题】:How can I test that a method has been called during runtime with minitest?如何在运行时使用 minitest 测试方法是否被调用?
【发布时间】:2017-01-26 15:39:10
【问题描述】:

我如何测试Geokit::Geocoders::MultiGeocoder.geocode(generate_address) 仅在保存后才被调用的事实。我应该以不同的方式编写代码吗?

请帮忙。

`

https://gist.github.com/bennacer860/b67583afee1bb9255938a3a621a80a54

class Playspace < ActiveRecord::Base
  before_validation :geocode_address, on: [:create, :update]

  def geocode_address
     geo = Geokit::Geocoders::MultiGeocoder.geocode(generate_address)
    # puts geo
    if geo.success
      self.lat = geo.lat
      self.lng = geo.lng
      self.state_code = geo.state_code
      self.country_code = geo.country_code
      self.geolocated_at = Time.now.utc
    else
     errors.add(:address, "Could not Geocode address #{generate_address}") 
    end
 end

  def did_address_change?
    %w( address city state_code country_code postal_code lat lng  ).each do |column|
      return true if (self.send("#{column}_changed?"))
    end
    false
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby minitest


    【解决方案1】:

    我建议使用 VCR 模拟您的外部 API 调用。事实上,您在代码中使用的 gem 使用 VCR 作为其own test suite

    一旦您在测试中设置了 VCR,它们可能包含如下内容:

    VCR.use_cassette("geocode") do
      playspace.geocode_address
      # Check that one of the columns changed
      assert playspace.did_address_change?
    end
    

    【讨论】:

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