【问题标题】:How to test controller action that uses puntopagos and rest-client?如何测试使用 puntopagos 和 rest-client 的控制器操作?
【发布时间】:2014-07-29 01:12:58
【问题描述】:

我有一个控制器,它有一个名为create 的 POST 操作。在创建操作中,我使用 puntopagos gem 类 (PuntoPagos::Request),该类使用 rest-client gem 向 API 发送 POST:

class SomeController < ApplicationController

  def create
    request = PuntoPagos::Request.new
    response = request.create
    #request.create method (another method deeper, really)
    #does the POST to the API using rest-client gem.

    if response.success?    
      #do something on success
    else
      #do something on error
    end
  end

end

如何使用 RSpec 存根其余客户端请求和响应以测试我的创建操作?

【问题讨论】:

    标签: ruby-on-rails testing rspec stub rspec3


    【解决方案1】:

    只需存根 PuntoPagos::Request.new 并继续存根:

    response = double 'response'
    response.stub(:success?) { true }
    request = double 'request'
    request.stub(:create) { response }
    PuntoPagos::Request.stub(:new) { request }
    

    这是一个成功的请求;再次使用 success? 存根返回 false 以测试该分支。

    一旦你完成了这项工作,请查看stub_chain 以减少打字次数来做同样的事情。

    话虽如此,最好将PuntoPagos 的东西提取到一个具有更简单接口的单独类中:

    class PuntoPagosService
      def self.make_request
        request = PuntoPagos::Request.new
        response = request.create
        response.success?
      end
    end
    

    那你就可以了

    PuntoPagosService.stub(:make_request) { true }
    

    在你的测试中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-26
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 2018-02-16
      • 2011-07-02
      • 1970-01-01
      相关资源
      最近更新 更多