0

という名前の POST アクションを持つコントローラーがありcreateます。create アクションでは、 rest-client gemを使用して API への POST を行うpuntopagos gemクラス ( PuntoPagos::Request) を使用します。

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 を使用して、残りのクライアントの要求と応答をスタブするにはどうすればよいですか?

4

1 に答える 1

1

スタブして、スタブPuntoPagos::Request.newを続けます。

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

これでリクエストが成功しました。そのブランチをテストするsuccess?ために戻るには、stubbed でもう一度実行します。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 }

あなたのテストで。

于 2014-07-29T04:40:15.567 に答える