Ryman1981
Ryman1981

Reputation: 11

Rails / RSpec: How to test Rails action with third party API?

class SessionsController < ApplicationController::Base  
  def create
      result = verify_sms_code(params[:session][:phone], params[:session][:code]
       if result['code'] == 200
         render json: {code: 200, msg: 'success'}
       else
         render json: {code: 404, msg: 'failed'}
       end
    end
end

The verify_sms_code method invokes third party API from network, the API returns JSON result for validation short message.

How can I test create action? Thanks

Upvotes: 0

Views: 1336

Answers (3)

Rohan Pujari
Rohan Pujari

Reputation: 838

You can stub method making external api call i.e verify_sms_code in your case. You can write something like

SessionsController.any_instance.stub(:verify_sms_code).and_return({code: 200, data: ''})

When you write above code whenever you use verify_sms_code inside SessionsController it will return the hash that you provide i.e {code: 200, data: ''}

If you are using rspec 3 and above, you can mock verify_sms_code as following inside controller.

allow(controller).to receive(:verify_sms_code).and_return({code: 200, data: ''})

Reference link:

https://www.relishapp.com/rspec/rspec-mocks/v/2-6/docs/method-stubs/stub-on-any-instance-of-a-class

http://rspec.info/documentation/3.4/rspec-mocks/

There are also other ways to mock. Check below link

https://robots.thoughtbot.com/how-to-stub-external-services-in-tests

Example:

it "does something" do   
  SessionsController.any_instance.stub(:verify_sms_code).and_return({code: 200, data: "success data"})
end

it "does other thing" do 
   SessionsController.any_instance.stub(:verify_sms_code).and_return({code: 404, data: "error data"})
end

Upvotes: 1

jvillian
jvillian

Reputation: 20263

I use webmock and like it quite a lot. I get a lot of control over headers, params, return content, return headers, return status, etc. But, not a lot of overhead.

I put all of my stub_requests into a shared set of files then include them en masse via rails_helper.rb. That way, I can reuse my stub_requests throughout my test suite.

Upvotes: 0

Flip
Flip

Reputation: 6761

I use the VCR gem for testing actions that make API calls. It lets you record API responses to use them in tests.

https://github.com/vcr/vcr

Upvotes: 0

Related Questions