puntopagos とrest-clientを使用するコントローラーアクションをテストするにはどうすればよいですか?
-
20-12-2019 - |
質問
という名前のPOSTアクションを持つコントローラーがあります create
. 。作成アクションでは、 プントパゴスの宝石 クラス (PuntoPagos::Request
) を使用します。 残りのクライアント宝石 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 を使用して、作成アクションをテストするために REST クライアントのリクエストとレスポンスをスタブするにはどうすればよいですか?
解決
スタブのみ 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 }
あなたのテストで。
所属していません StackOverflow