Testing: mocking vs stubbing
This course covers rspec-mocks, the gem bundled with rspec-rails, and the difference between a stub and a mock. A stub, set with allow, replaces a return value and never fails. A mock, set with expect, fails the test when the expected call never happens. The lessons draw on this app's spec files. They cover instance_double, which checks stubbed methods against a real class, and compare two CompleteLessonService specs with opposite stubbing choices. A hand-built test double shows the mechanism, and a Ruby challenge closes the course.
What you'll learn
- ✓How a stub with allow(...).to receive(...).and_return(...) replaces a return value
- ✓How a mock with expect(...).to receive(...) fails a test when a call never happens
- ✓How instance_double checks stubbed methods against a real class's instance methods
- ✓When to stub a collaborator and when to test with real objects
- ✓How to build a small stub and mock object by hand with method_missing
What rspec-mocks is, and how much this app already uses it
rspec-mocks ships as part of rspec-rails, the testing framework the earlier testing courses already relied on; bundle show rspec-mocks reports version 3.13.8. There's nothing to install for this course. It already runs in this app every time bundle exec rspec does.
Read the full lesson free →Curriculum
7 lessonsWhat rspec-mocks is, and how much this app already uses it
Introduces rspec-mocks, shows where this app's specs already use it, and separates stubs from mocks.
A stub replaces a return value, and never fails however it's called
Shows how allow replaces a return value without failing, using the stubbed ImageProcessing::Vips chain as an example.
A mock asserts a call happened, and fails the test if it never does
Explains how expect asserts a call with given arguments and fails through the verify_messages_received check.
instance_double: a stub that checks itself against the real class
Compares a plain double with instance_double, which rejects methods missing from the real class, including class methods.
When stubbing a collaborator earns its place: this app's CompleteLessonService
Compares a service spec using real objects with a request spec that stubs the whole CompleteLessonService.
Building a test double from scratch, no gem needed
Rebuilds the core stub and mock mechanism in plain Ruby using method_missing and two hashes.
Putting it together: one gem, two tools, one decision each time
Reviews stubs, mocks, instance_double and the hand-built double, then sets a Ruby challenge without RSpec.