Welcome to our lesson on using Fakes as test doubles in Test-Driven Development (TDD) with Ruby and RSpec. In this lesson, you'll explore how fakes can streamline your testing by simulating real-world components. Our journey so far has exposed you to various test doubles like dummies, stubs, spies, and mocks. Now, we'll dive into fakes, which enable you to create realistic implementations that mirror complex dependencies, making your tests more robust and reliable. As always, we'll practice the TDD cycle: Red, Green, Refactor, as we see how fakes fit into our testing strategy.
Let's see how to implement a simple fake: an InMemoryUserRepository
. This serves as a stand-in for a real database repository, providing controlled behavior for our tests.
Create in_memory_user_repository.rb
:
Explanation:
- We create in-memory storage for users using a hash (
@users
). - Each function simulates typical database operations like
create
,find_by_id
, andfind_all
. - The
clear
method ensures data isolation between tests, a crucial feature for repeatable outcomes.
By using a controlled data store, we make sure our tests focus on business logic and are not dependent on an external database. Fakes are often quite complicated (compared to mocks or stubs) to build because they mimic the behavior of the real thing. They can be used to verify the state after your code acts on the fake, which can be really useful when you are trying to mimic the environment as best as possible without introducing the uncertainty or delay that the real implementation would introduce.
Next, we will use the fake repository to test a UserService
.
- Red: Write Failing Tests
In user_service_spec.rb
:
This test example assumes that the UserService
logic is not implemented yet, resulting in a failing test.
- Green: Implement Minimal Code
Example implementation in user_service.rb
:
This shows a minimal implementation that satisfies the test criteria, demonstrating how the test can be made to pass.
In this lesson, we explored the implementation and use of fakes in TDD, specifically via an in-memory repository for user management. Remember the steps of TDD:
- Red: Write a test that fails first, setting clear goals for implementation.
- Green: Implement just enough code to make your test pass.
- Refactor: Improve code quality without altering functionality.
Leverage the practice exercises to reinforce these concepts with hands-on examples. Congratulations on navigating the complexities of testing with fakes; your commitment is paving the way for building efficient, scalable applications. This is the final lesson of the course, so kudos for reaching this milestone! Keep exploring and applying TDD principles in your projects.
