I am using TestUnit and would like to determine if a function is called. I have a method in a class called Person which I set to be called '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). 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With