2017-01-31 57 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