Previously we tested model and controller and learned some common test methods. Now we will go deep into several test topics. The first is to use a Mock object.
In many cases, our programs are dependent on the actual environment, such as the current shopping cart, the bank account on the network needs to be connected during remittance and checkout, this requires an internet environment for testing. For example, we have created a payment_gateway.rb in the model directory to process operations related to network banking. We write in the save_order method of store_control.rb as follows:
Gateway = PaymentGateway. new
Response = gateway. collect (: login => 'username ',
: Password => 'Password ',
: Amount => cart. total_price,
: Card_number => @ order. card_number,
: Expiration => @ order. card_expiration,
: Name => @ order. name)
We use the username and password of the bank account in the collect method of gateway, but in this way, we must have a real internet environment during the test, and, we don't want to operate the bank account every time we run the test.
Therefore, what we need is a substitute for a false object (mock) or PaymentGateway. Here, rails provides us with convenience, all we need to do is create a payment_gateway.rb file in the test/mock/test/directory to overwrite the payment_gateway.rb file in the app/models directory. Note that, the file names must be identical. Mock file content:
Require 'models/payment_gateway'
Class PaymentGateway
Def collect (request)
# I'm a mocked out method
: Success
End
End
This means that we use the mock object to replace the PaymentGateway under the real models directory, and the collect method also returns a false response.
During the test, Rails first queries the directory where the mock object is located. In this way, the classes under the mock directory are loaded, rather than the classes under the real models directory.
In this way, by using mock objects, we can focus on important and high-priority tests, and rails makes these jobs easy.