كيفية اختبار إجراء وحدة التحكم التي تستخدم puntopagos وrest-client؟

StackOverflow https://stackoverflow.com//questions/25006798

سؤال

لدي وحدة تحكم مع إجراء POST اسمه create.في إجراء الإنشاء أستخدم ملف جوهرة بونتوباغوس فصل (PuntoPagos::Request) الذي يستخدم جوهرة بقية العميل لإنشاء مشاركة إلى واجهة برمجة التطبيقات:

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، إيقاف طلب العميل المتبقي والاستجابة له من أجل اختبار إجراء الإنشاء الخاص بي؟

هل كانت مفيدة؟

المحلول

مجرد كعب 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 }

في الاختبار الخاص بك.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top