Skip to content

Added a section on Method Stubs vs Expectations #142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -941,6 +941,40 @@ expect(notifier).to receive(:notify).with('suspended as')

NOTE: If you stub a method that could give a false-positive test result, you have gone too far.

=== Method Stubs vs Expectations

Prefer stubs over expectations when setting up test doubles. This approach leads to more maintainable and clearer tests by separating the setup of test doubles from the verification of their usage. Using `allow` for stubs makes the intent clearer - you're setting up the test environment rather than making assertions about behavior.

When you need to verify that a method was called, you can add an expectation with `have_received` after the fact. This separation of concerns makes tests easier to understand and maintain.

[source,ruby]
----
# bad - expecting instance double
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this could still be good but then the testing actual method would be better and verifying instance double even better

article = instance_double('Article')
expect(article).to receive(:author).and_return(nil)


presenter = described_class.new(article)
expect(presenter.title).to include('by an unknown author')


# good - testing actual method
article = instance_double('Article')
allow(article).to receive(:author).and_return(nil)

presenter = described_class.new(article)
expect(presenter.title).to include('by an unknown author')


# good - verifying instance double
article = instance_double('Article')
allow(article).to receive(:author).and_return(nil)

presenter = described_class.new(article)
expect(presenter.title).to include('by an unknown author')
expect(article).to have_received(:author)
----

=== Dealing with Time

Always use https://github.com/travisjeffery/timecop[Timecop] instead of stubbing anything on Time or Date.
Expand Down