How to test rails controller action with another method

25 views
Skip to first unread message

Ryman

unread,
Mar 2, 2016, 2:46:07 AM3/2/16
to rspec
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

I want to mock verify_sms_code method returns JSON result,e.g {'code':200, data:'correct'} or {'code':404, data:'incorrect'} ,how can I test this action with verify_sms_code method different return values?  Thanks!

Jon Rowe

unread,
Mar 2, 2016, 7:17:55 PM3/2/16
to rs...@googlegroups.com
Assuming you’re doing a controller spec you could do something like `allow(controller).to receive(:verify_sms_code) { { ‘code’ => 200 } }`

Jon Rowe
---------------------------

--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/848b2139-5848-4b41-a471-6c42085fe5df%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ryman

unread,
Mar 3, 2016, 3:03:09 AM3/3/16
to rspec
 Thanks Jon, sorry my bad English. The `allow(controller).to receive(:verify_sms_code) { { ‘code’ => 200 } }` only sets the create action returns {'code':200} ,but I want to let `verify_sms_code` method returns {'code':200} or {'code': 404} ,so that I can test create action with `verify_sms_code` method different returns 

在 2016年3月3日星期四 UTC+8上午8:17:55,Jon Rowe写道:

Jon Rowe

unread,
Mar 3, 2016, 3:22:21 AM3/3/16
to rs...@googlegroups.com
Yep, the allow only lasts until the end of the test, in your next test set the code to 404 to test the other value.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/8410970d-fd70-48e4-9c93-87ef958c8496%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages