Ton*_*ony 5 unit-testing ruby-on-rails
我正在使用TestUnit,并想确定是否调用了一个函数.我在一个名为Person的类中有一个方法,我将其设置为'before_update':
def geocode_if_location_info_changed
if location_info_changed?
spawn do
res = geocode
end
end
end
Run Code Online (Sandbox Code Playgroud)
然后我有一个单元测试:
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
Run Code Online (Sandbox Code Playgroud)
如何确保调用"地理编码"方法?对于我想确保在位置信息未更改时不调用的情况,这一点更为重要.
谢谢!
使用摩卡.这会测试过滤器的逻辑:
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
Run Code Online (Sandbox Code Playgroud)