简体   繁体   English

测试是否在Ruby on Rails单元测试中调用函数

[英]Test if a function is called in a Ruby on Rails unit test

I am using TestUnit and would like to determine if a function is called. 我正在使用TestUnit,并想确定是否调用了一个函数。 I have a method in a class called Person which I set to be called 'before_update': 我在一个名为Person的类中有一个方法,我将其设置为'before_update':

def geocode_if_location_info_changed
    if location_info_changed?
      spawn do
        res = geocode
      end
    end
  end

Then I have a unit test: 然后我有一个单元测试:

def test_geocode_if_location_info_changed
  p = create_test_person
  p.address = "11974 Thurloe Drive"
  p.city = "Baltimore"
  p.region = Region.find_by_name("Maryland")
  p.zip_code = "21093"
  lat1 = p.lat
  lng1 = p.lng

  # this should invoke the active record hook
  # after_update :geocode_if_location_info_changed
  p.save
  lat2 = p.lat
  lng2 = p.lng
  assert_not_nil lat2
  assert_not_nil lng2
  assert lat1 != lat2
  assert lng1 != lng2

  p.address = "4533 Falls Road"
  p.city = "Baltimore"
  p.region = Region.find_by_name("Maryland")
  p.zip_code = "21209"

  # this should invoke the active record hook
  # after_update :geocode_if_location_info_changed
  p.save

  lat3 = p.lat
  lng3 = p.lng
  assert_not_nil lat3
  assert_not_nil lng3
  assert lat2 != lat3
  assert lng2 != lng3
end

How can I ensure that the "geocode" method was called? 如何确保调用“地理编码”方法? This is more important for the case where I want to make sure it is not called if location information has not changed. 对于我想确保在位置信息未更改时不调用的情况,这一点更为重要。

Thanks! 谢谢!

Use mocha. 使用摩卡。 This tests the logic of your filter: 这会测试过滤器的逻辑:

def test_spawn_if_loc_changed
  // set up omitted
  p.save!
  p.loc = new_value
  p.expects(:spawn).times(1)
  p.save!
end

def test_no_spawn_if_no_data_changed
  // set up omitted
  p.save!
  p.other_attribute = new_value
  p.expects(:spawn).times(0)
  p.save!
end

What you need are mock objects (see Mockobjects and Mocks aren't stubs for more general info). 你需要的是模拟对象(有关更多常规信息,请参阅MockobjectsMocks 不是存根 )。 RSpec has support for them , and there are other standalone libraries out there (for example, Mocha ), which should help you if you don't need to switch to RSpec. RSpec 支持它们 ,并且还有其他独立库(例如, Mocha ),如果您不需要切换到RSpec,它们可以帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM