2014-01-27 69 views
0

我有一個類負責處理支付網關的某些響應。如何在Rspec中測試此類行爲

比方說:

class PaymentReceiver 
    def initialize(gateway_response) 
    @gateway_response = gateway_response 
    end 

    def handle_response 
    if @gateway_response['NC_STATUS'] != '0' 
     if order 
     order.fail_payment 
     else 
     raise 'LackOfProperOrder' 
     # Log lack of proper order 
     end 
    end 
    end 

    private 

    def order 
    @order ||= Order.where(id: @gateway_response['orderID']).unpaid.first 
    end 
end 

在從支付有效載荷我已經NC_STATUS 如果支付成功,orderID這是指Order ActiveRecord class by id`負責信息。

我想測試行爲(在rspec的): 如果PaymentReceiver接收響應,其中NC_STATUS = 0發送至fail_payment通過orderID稱爲特定Order對象!。

你將如何處理測試?我認爲,也可能是設計不好...

回答

0

你必須重構,以刪除SRPDIR違反原則。 下面的東西我會說:

class PaymentReceiver 
    def initialize(response) 
    @response = response 
    end 

    def handle_response 
    if @response.success? 
     @response.order.pay 
    else 
     @response.order.fail_payment 
    end 
    end 
end 

# it wraps output paramteres only ! 
class PaymentResponse 
    def initialize(response) 
    @response = response 
    end 

    def order 
    # maybe we can check if order exists 
    @order ||= Order.find(@response['orderID'].to_i) 
    end 

    def success? 
    @response['NCSTATUS'] == '0' 
    end 
end 

p = PaymentReceiver.new(PaymentResponse({'NCSTATUS' => '0' })) 
p.handle_response 

然後測試一切都很容易。