2016-04-23 101 views
0

我正在嘗試學習MiniTest並通過這樣做,我已經開始測試使用PayPal API批准/拒絕信用卡付款的應用程序之一。以下是我在測試Payment類中的購買方法的嘗試。 (CREDIT_CARD原本是一個私有方法,轉移到公衆進行測試)MiniTest ::對於應該返回true的測試返回false的斷言

payment.rb

require "active_merchant/billing/rails" 

class Payment < ActiveRecord::Base 
    belongs_to :order 
    attr_accessor :card_number, :card_verification 

    def purchase(card_info, billing_info) 
    if credit_card(card_info).valid? 
     response = GATEWAY.purchase(price_in_cents, credit_card(card_info), purchase_options(billing_info)) 
     @paypal_error = response.message 
     response.success? 
    end 
    end 

    def price_in_cents 
    (@total.to_f * 100).round 
    end 


    def credit_card(card_info) 
     @credit_card ||= ActiveMerchant::Billing::CreditCard.new(card_info) 
    end 

    private 

    def purchase_options(billing_info) 
    billing_info 
    end 

end 

payment_test.rb

require 'test_helper' 
require "active_merchant/billing/rails" 

class PaymentTest < ActiveSupport::TestCase 
    setup do 
    @card_info = { 
     brand: "Visa", 
     number: "4012888888881881", 
     verification_value: "123", 
     month: "01", 
     year: "2019", 
     first_name: "Christopher", 
     last_name: "Pelnar", 
    } 
    @purchase = Payment.new 
    end 

    test "purchase" do 
    assert @purchase.credit_card(@card_info).valid?, true 
    end 

end 

錯誤信息運行rake test後:

-------------------------- 
PaymentTest: test_purchase 
-------------------------- 
    (0.1ms) ROLLBACK 
    test_purchase             FAIL (0.02s) 
Minitest::Assertion:   true 
     test/models/payment_test.rb:20:in `block in <class:PaymentTest>' 


Finished in 0.03275s 
1 tests, 1 assertions, 1 failures, 0 errors, 0 skips 

回答

3

MiniTest::Assertionsassert方法調用使用語法assert(test, msg = nil)您的測試返回true的原因是您選擇使用的消息。 assert_equal方法需要2個值進行比較。此外,而不是使私有方法公開,您可以使用.send方法是這樣的:

assert @purchase.send(:credit_card,@card_info).valid? 

還可以更改設置的函數定義:

def setup 
    # setup logic 
end 

,使輸出更冗長(捕捉ActiveMerchant錯誤),請嘗試以下操作:

test "purchase" do 
    credit_card = @purchase.send(:credit_card, @card_info) 
    assert credit_card.valid?, "valid credit card" 
    puts credit_card.errors unless credit_card.errors.empty? 
end 

閱讀rubyforge API我認爲信用卡類型應設置爲測試僞造的。

+0

我改變了方法回到私人和運行測試與你提供的邏輯,這就是它返回的:Minitest :: Assertion:斷言失敗,沒有給出的消息。 – Ctpelnar1988

+0

感謝您糾正我的私人方法測試問題btw 。我一直在努力嘗試它的語法。 – Ctpelnar1988

+1

您是否更改設置進入def設置? –

相關問題