在开发环境中为外部呼叫创建虚假行为 [英] Create fake behavior for external call in development environment

查看:68
本文介绍了在开发环境中为外部呼叫创建虚假行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行需要搜索外部API的代码,但是在开发过程中,我无法访问此API,因此我当前用于运行服务器并浏览系统的解决方案是:

I'm doing a code that need to search a external API, but during development I haven't access to this API, so my current solution to run the server and navigate through the system is:

def api_call
   return { fake: 'This is a fake return' } if Rails.env.development?

   # api interaction code
   # ...
end

这让我的代码很脏,所以我的问题是:有一种模式(或更好的方法)可以做到这一点?

This let my code dirt, so my question is: There are a pattern (or a better way) to do this?

推荐答案

我使用的模式是将api对象替换为一种在开发过程中伪造所有方法的对象。

The pattern I use is to replace api object with one that fakes all methods when in development.

class Api
  def query
    # perform api query
  end
end

class FakeApi
  def query
    { fake: 'This is a fake return' }
  end
end

# config/environments/production.rb
config.api = Api.new

# config/environments/test.rb
# config/environments/development.rb
config.api = FakeApi.new

# then

def api_call
  Rails.configuration.api.query # no branching here! code is clean
end

基本上,您有两个类, Api 可以完成实际工作,而 FakeApi 可以返回预先烘焙的伪造响应。然后,您可以使用Rails的环境配置在不同的环境中设置不同的api。这样,您的客户端代码(调用 #query )就不必关心当前环境。

Basically, you have two classes, Api which does real work and FakeApi that returns pre-baked faked responses. You then use Rails' environment configuration to set different apis in different environments. This way, your client code (that calls #query) doesn't have to care about current environment.

这篇关于在开发环境中为外部呼叫创建虚假行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆