2017-01-31 6 views
2

아래의 경우 테스트 할 내용과 방법을 이해하는 데 문제가 있습니다.외부 API를 호출하는 모델 인스턴스 메서드를 테스트하는 방법

나는 주소 모델에서 다음 인스턴스 메소드를

validate :address, on: [:create, :update] 

def address 
    check = CalendarEventLocationParsingWorker.new.perform("", self.structured, true) 
    if check[:code] != 0 
     errors.add(:base,"#{self.kind.capitalize} Address couldn't be analysed, please fill up as much fields as possible.") 
    else 
     self.lat = check[:coords]["lat"] 
     self.lon = check[:coords]["lng"] 
    end 
    end 

기본적으로 그 주소가 유효한 경우 타사 API로 생성 및 업데이트 후크 및 검사 호출 방법에 관한 것이다. 어떻게하면 제 3 자 API를 실제로 호출하지 않고이 테스트를 격리하여 테스트 할 수 있습니까?

나는 모조품과 스텁에 관해 읽었지만 나는 아직 얻지 못했다. 모든 통찰력을 환영합니다. Rspec, shouldc matchers 및 공장 소녀를 사용하여. 한 번 테스트를 실행할 수 있습니다 vcr

stub_request(:get, "your external api url") 
    .to_return(code: 0, coords: { lat: 1, lng: 2 }) 

# test your address method here 

과 외부 API를, 기록에 실제 전화를 할 것입니다 :

답변

1

사용 webmock 또는 vcr 보석 외부 API 응답

webmock와

예를 스텁 그것의 공명은 .yml 파일에 저장하고 나중에 모든 테스트에서 다시 사용합니다. 외부 API 응답이 변경되면 .yml 파일을 삭제하고 새로운 샘플 응답을 기록 할 수 있습니다.

당신은 원하는 값을 반환 할 CalendarEventLocationParsingWorker의 인스턴스에

구문 perform 방법을 스텁 수

+0

헤이 감사 , 실제 요청을하지 않고 할 수 있습니까? 한 번도 아니지만? –

+0

@PetrosKyriakou 예, 이것을 위해 webmock을 사용하십시오. –

0

:

allow_any_instance_of(Class).to receive(:method).and_return(:return_value) 

예 :

allow_any_instance_of(CalendarEventLocationParsingWorker).to receive(:perform).and_return({code: 0}) 

참조 : 이것에 대한 Allow a message on any instance of a class