ruby-on-rails - 使用rails3模拟外部API对象

标签 ruby-on-rails ruby-on-rails-3 mocking

我想模拟/ stub :

@the_bill = GovKit::OpenCongress::Bill.find_by_idents("112-s368").first

用于我的测试。

它返回以下对象,我想出于测试目的修复该对象:

--- !ruby/object:GovKit::OpenCongress::Bill 
bill_type: s
co_sponsors: 
- !ruby/object:GovKit::OpenCongress::Person {}

id: 68340
introduced: 1297836000
most_recent_actions: 
- result: 
  created_at: "2011-02-17T07:45:50Z"
  govtrack_order: 
  amendment_id: 
  text: Read twice and referred to the Committee on Agriculture, Nutrition, and Forestry.
  date: 1297836000
  how: 
  id: 287979
  vote_type: 
  type: BillAction
  roll_call_id: 
  action_type: action
  datetime: "2011-02-16T00:00:00Z"
  where: 
  bill_id: 68340
  roll_call_number: 
- result: 
  created_at: "2011-02-17T07:45:49Z"
  govtrack_order: 
  amendment_id: 
  text: 
  date: 1297836000
  how: 
  id: 287978
  vote_type: 
  type: BillAction
  roll_call_id: 
  action_type: introduced
  datetime: "2011-02-16T00:00:00Z"
  where: 
  bill_id: 68340
  roll_call_number: 
number: 368
plain_language_summary: 
recent_blogs: []

我尝试过 Factory_girl (做不到,不是基于模型的对象)、Fabrication (仍然存在相同的问题)和 OpenStruct,可能是可能的,但在将 yaml 转换为 OpenStruct 并将模拟放在正确的位置时遇到了困难。

现在,我正在测试中进行 api 调用,而不是我想要的。我认为 webmock 是我的解决方案,但我在文档中找不到如何加载一个简单的对象。

最佳答案

尝试VCR用于模拟 API。大约 6 个月前我有完全相同的问题,直到最近才发现这个库。它完全满足您的需要,将缓存对象以供稍后测试,但也可以定期自动刷新它们。到目前为止,这无疑是我为此找到的最佳解决方案。

关于ruby-on-rails - 使用rails3模拟外部API对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6337362/

相关文章:

Rails 中每个 View 的 JavaScript 文件

ruby-on-rails - PG :Error relation does not exist

ruby-on-rails - 请求 URI 过大错误 - 摆脱 GET?

ruby-on-rails-3 - 将 Rails 应用程序从 1.2.3 升级到 3.1.0?

ruby-on-rails - facebook 身份验证后与门卫进行身份验证

c++ - 模拟类来测试它的方法

ruby-on-rails - Rails Heroku 部署错误 - 推送被拒绝

mysql - rails if 语句,如果没有找到记录

c# - 使用 Moq 进行单元测试

unit-testing - 梅克和测试驱动开发工作流程?