2009-11-04 3 views
5

TestUnit을 사용하고 있으며 함수가 호출되었는지 확인하려고합니다.Ruby on Rails 유닛 테스트에서 함수가 호출되는지 테스트합니다.

def geocode_if_location_info_changed 
    if location_info_changed? 
     spawn do 
     res = geocode 
     end 
    end 
    end 

그럼 내가 단위 테스트가 : 나는 'before_update'라고 설정 클래스라는 사람의 방법이 어떻게 보장 할 수

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 

을 그 "지오"방법 라고? 이것은 위치 정보가 변경되지 않으면 호출되지 않도록하려는 경우 더욱 중요합니다.

감사합니다.

답변

6

모카를 사용하십시오. 필터의 논리를 테스트합니다.

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 
+0

'p.expects (: geocode_if_location_info_changed) .times (1)'를 원한다고 생각하지만이 답변에 동의합니다. 여기 모카를 사용하면 괜찮습니다. 필터 전에는 내 생각에 공동 작업자와 매우 비슷하게 보입니다. –

+0

필자는 before 필터의 논리를 테스트하려고 시도하고 있었고 * spawn *이 if 내부의 첫 번째 항목입니다. before 필터 호출을 테스트하는 경우 "before_filter"가 존재하고 레일이 작동하고 있는지 테스트하는 것이 좋습니다.하지만 필터 내의 로직을 얻으려고하는 것처럼 보입니다. – ndp

+0

좋은 점 - 그 각도를 볼 수 있습니다. –

1

모의 개체가 필요합니다 (자세한 내용은 MockobjectsMocks aren't stubs 참조). RSpec에는 support for them이 있으며 다른 독립형 라이브러리가 있습니다 (예 : Mocha). RSpec으로 전환 할 필요가없는 경우 도움이됩니다.

+0

여기에서 모의해야 할 사항은 무엇입니까? 필자의 개인 대상은 테스트중인 시스템이며 마틴 파울러 (Martin Fowler)의 기사에 따르면 공동 작업자는 모의 객체를 사용해야합니다. – Tony