O'Reilly logo

Rails 4 Test Prescriptions by Noel Rappin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. In other words, a mock is like a stub with attitude, expecting—nay, demanding—that its parameters be matched in the test or else we 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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required