Junior Track Roadmap

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
Free preview · Lesson 1 3 min read

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 lessons
Type to start searching...