加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 测试在Ruby on Rails单元测试中是否调用了函数

发布时间:2020-12-17 03:25:56 所属栏目:百科 来源:网络整理
导读:我正在使用TestUnit,并想确定是否调用了一个函数.我在一个名为Person的类中有一个方法,我将其设置为’before_update’: def geocode_if_location_info_changed if location_info_changed? spawn do res = geocode end end end 然后我有一个单元测试: def t
我正在使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读