Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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!

like image 504
Tony Avatar asked Nov 04 '09 21:11

Tony


2 Answers

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
like image 62
ndp Avatar answered Oct 14 '22 00:10

ndp


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.

like image 1
pantulis Avatar answered Oct 14 '22 01:10

pantulis