[英]Test if a function is called in a Ruby on Rails unit test
我正在使用TestUnit,並想確定是否調用了一個函數。 我在一個名為Person的類中有一個方法,我將其設置為'before_update':
def geocode_if_location_info_changed
if location_info_changed?
spawn do
res = geocode
end
end
end
然后我有一個單元測試:
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
如何確保調用“地理編碼”方法? 對於我想確保在位置信息未更改時不調用的情況,這一點更為重要。
謝謝!
使用摩卡。 這會測試過濾器的邏輯:
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
你需要的是模擬對象(有關更多常規信息,請參閱Mockobjects和Mocks 不是存根 )。 RSpec 支持它們 ,並且還有其他獨立庫(例如, Mocha ),如果您不需要切換到RSpec,它們可以幫助您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.