How do I stub things in MiniTest?

前端 未结 8 871
面向向阳花
面向向阳花 2020-12-02 09:46

Within my test I want to stub a canned response for any instance of a class.

It might look like something like:

Book.stubs(:title).any_instance().ret         


        
8条回答
  •  -上瘾入骨i
    2020-12-02 10:10

    I thought I'd share an example that I built upon the answers here.

    I needed to stub a method at the end of a long chain of methods. It all started with a new instance of a PayPal API wrapper. The call I needed to stub was essentially:

    paypal_api = PayPal::API.new
    response = paypal_api.make_payment
    response.entries[0].details.payment.amount
    

    I created a class that returned itself unless the method was amount:

    paypal_api = Class.new.tap do |c|
      def c.method_missing(method, *_)
        method == :amount ? 1.25 : self
      end
    end
    

    Then I stubbed it in to PayPal::API:

    PayPal::API.stub :new, paypal_api do
      get '/paypal_payment', amount: 1.25
      assert_equal 1.25, payments.last.amount
    end
    

    You could make this work for more than just one method by making a hash and returning hash.key?(method) ? hash[method] : self.

提交回复
热议问题