Tuesday, September 19, 2017

Stubs, Mocks, and Spies in Rspec

There's a number of different terms we use in testing to describe how we're setting up the tests. Are we stubbing? Mocking? Spying? All of the above? What do they even mean?

1. Stubs

These are just canned responses. You stub out methods so that when they're called, they just return something (anything you want). If they're not called, nothing happens. 

Rspec stubbing: https://relishapp.com/rspec/rspec-mocks/v/2-14/docs/method-stubs

Example

allow(obj).to receive(:message).and_return(:value)

You can do this either both real objects and doubles.

2. Spies

These are objects that you set up with canned responses (like stubs) that also record information about the calls made to that method (was it called? what was it called with? How many times?). 

Rspec

Example

allow(Invitation).to receive(:deliver) 

or

invitation = spy('invitation')

Followed by the assertion

expect(invitation).to have_received(:deliver)

3. Mocks

These are objects that have already been instrumented with expectations. They're like spies in that actions are recorded but they also go a step further to automatically verify the behavior when the test is exercised.

Example

logger = double("logger")
account = Account.new logger

expect(logger).to receive(:account_closed)

account.close

State verification vs Behavior verification 

Verification is the act of verifying that something occurred in some manner. In testing, we rely on either state verification or behavior verification to ensure that objects are behaving in the way we expect them to. 

In the testing world, state verification is verifying the test through the state of an object. What's the current value of variable X? In other words, what's the current status of this object? Does it match up with expectations? 

Behavior verification takes a different approach. Behavior verification is not concerned with what state the object is in - it's only concerned with the fact that certain actions occurred in some manner (regardless of how they changed the objects state). 

According to Martin Fowler, only mocks insist on behavior verification. In other words, unlike stubs and spies, only mocks are preprogrammed to perform behavior verification. With mocks, you don't really have a choice to do state verification. 






1 comment:

  1. I was diagnosed as HEPATITIS B carrier in 2013 with fibrosis of the
    liver already present. I started on antiviral medications which
    reduced the viral load initially. After a couple of years the virus
    became resistant. I started on HEPATITIS B Herbal treatment from
    ULTIMATE LIFE CLINIC (www.ultimatelifeclinic.com) in March, 2020. Their
    treatment totally reversed the virus. I did another blood test after
    the 6 months long treatment and tested negative to the virus. Amazing
    treatment! This treatment is a breakthrough for all HBV carriers.

    ReplyDelete