2017-01-31 108 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,如果地址是有效的方法。我怎樣才能測試這個隔離沒有真正的電話到第三方API,而是模擬響應?

我讀過關於嘲笑和存根的問題,但我還沒有完全理解它們。任何見解都值得歡迎。使用Rspec,shoulda匹配器和工廠女孩。

回答

1

使用webmockvcr寶石存根外部API響應

一個例子與webmock:

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

# test your address method here 

隨着vcr您可以一次運行測試,它將使外部API,記錄的實際通話它會對.yml文件產生影響,然後在以後的所有測試中重複使用它。如果外部api響應更改,您可以刪除.yml文件並記錄新的示例響應。

+0

嘿感謝這,我可以不做實際的請求嗎?雖然不是一次? –

+0

@PetrosKyriakou是的,使用webmock這個 –

0

您可以存根上的CalendarEventLocationParsingWorker任何實例perform方法返回所需的值

語法:

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

相關問題