Mock Expectations

A mock object retains the basic idea of the stub—returning a specified value without actually calling a live method—and adds the requirement that the specified method must be called during the test. A mock is like a stub with attitude, expecting—nay, demanding—that its parameters be matched in the test or else you get a test failure.

In RSpec, you use the expect method to create mock expectations. This can be applied to full or partial doubles:

 it ​"expects stuff"​ ​do
  mocky = double(​"Mock"​)
  expect(mocky).to receive(​:name​).and_return(​"Paul"​)
  expect(mocky).to receive(​:weight​).and_return(100)
  expect(mocky.name).to eq(​"Paul"​)
 end

This test fails:

 Failures:
  1) Project expects stuff
  Failure/Error: expect(mocky).to ...

Get Rails 5 Test Prescriptions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.