Question

I have a controller with a POST action named create. In the create action I use a puntopagos gem class (PuntoPagos::Request) that uses the rest-client gem to make a POST to an 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

How can I, with RSpec, stub the rest-client request and response in order to test my create action?

Was it helpful?

Solution

Just stub PuntoPagos::Request.new and keep on stubbing:

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

That's for a successful request; do it again with success? stubbed to return false to test that branch.

Once you've got that working, look in to stub_chain to do the same thing with less typing.

Having said that, it would be much better to extract the PuntoPagos stuff into a separate class with a simpler interface:

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

Then you can just do

PuntoPagosService.stub(:make_request) { true }

in your test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top