Come testare l'azione del controller che utilizza Puntopagos e Rest-client?
-
20-12-2019 - |
Domanda
Ho un controller con un'azione post denominata create
.Nella creazione di azione uso un Puntopagos Gem class (PuntoPagos::Request
) che utilizza Gemma del riposo-client per creare un post su un'API:
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
.
Come posso, con RSPEC, stub la richiesta di riposo-client e la risposta per testare la mia azione di creazione?
Soluzione
Just Stub PuntoPagos::Request.new
e mantieni lo stubbing:
response = double 'response'
response.stub(:success?) { true }
request = double 'request'
request.stub(:create) { response }
PuntoPagos::Request.stub(:new) { request }
.
è per una richiesta di successo;Fatelo di nuovo con success?
Storbbed per tornare false
per testare quel ramo.
Una volta che hai funzionato, guarda a stub_chain
per fare la stessa cosa con meno digitazione.
Avendo detto che, sarebbe molto meglio estrarre le cose Puntopagos in una classe separata con un'interfaccia più semplice:
class PuntoPagosService
def self.make_request
request = PuntoPagos::Request.new
response = request.create
response.success?
end
end
.
Allora puoi semplicemente fare
PuntoPagosService.stub(:make_request) { true }
.
nel tuo test.