RSpec Mock Object Example

前端 未结 5 1050
说谎
说谎 2021-01-30 13:13

I am new to mock objects, and I am trying to learn how to use them in RSpec. Can someone please post an example (a hello RSpec Mock object world type example), or a link (or any

5条回答
  •  时光取名叫无心
    2021-01-30 13:59

    Current (3.x) RSpec provides both pure mock objects (as in tokhi's answer) and partial mocking (mocking calls to an existing object). Here's an example of partial mocking. It uses expect and receive to mock an Order's call to a CreditCardService, so that the test passes only if the call is made without having to actually make it.

    class Order
      def cancel
         CreditCardService.instance.refund transaction_id
      end
    end
    
    describe Order do
      describe '#cancel' do
        it "refunds the money" do
          order = Order.new
          order.transaction_id = "transaction_id"
          expect(CreditCardService.instance).to receive(:refund).with("transaction_id")
          order.cancel
        end
      end
    end
    

    In this example the mock is on the return value of CreditCardService.instance, which is presumably a singleton.

    with is optional; without it, any call to refund would satisfy the expectation. A return value could be given with and_return; in this example it is not used, so the call returns nil.


    This example uses RSpec's current (expect .to receive) mocking syntax, which works with any object. The accepted answer uses the old rspec-rails mock_model method, which was specific to ActiveModel models and was moved out of rspec-rails to another gem.

提交回复
热议问题