Before we tested model and controller, we learned some common test methods, and now we're going to delve into a few topics about testing. The first is to use a mock object.
In many cases, our program and the actual environment have dependencies, such as the current shopping cart, in the remittance, checkout time to access the network bank account, which caused us to test the time must have an Internet environment. For example, we created a payment_gateway.rb in the model directory to handle network banking-related operations, which we wrote in the Save_order method of store_control.rb:
Gateway = paymentgateway.new
response = Gateway.collect (: Login => ' username ',
:p assword => ' password ',
: Amount => cart.total_price, Card_number =>
@order. Card_number: Expiration =>
@order. card_expi Ration,
: Name => @order. Name)
We use the username, password, and so on in the Collect method of the gateway, but we must have a real Internet environment when we test, and we don't want to actually have to operate the bank account every time we run the test.
So, what we need is a fake object (mock) or a substitute for paymentgateway, where rails provides convenience, all we have to do is create a payment_ in the test/mock/test/directory GATEWAY.RB file, to cover the PAYMENT_GATEWAY.RB in the App/models directory, note that the file names must be identical in both places. Contents of mock file:
Require ' Models/payment_gateway '
class Paymentgateway
def collect (Request)
# I ' m a mocked
out method : Success
End
This means that we use mock objects to replace the Paymentgateway in the real models directory, and the Collect method returns a false response.
When testing, rails looks in the same directory as the mock object, so that it loads the class under the mock directory, not the real models directory.
In this way, by using mock objects, we can focus on important, high-priority tests, and rails makes the work easier.