Unit, Integration and End-to-End Tests Trade Speed for Realism

In progress Testing

The testing pyramid sorts automated tests by scope. Unit tests check one function in isolation and run in milliseconds; integration tests check that components work together and need real resources such as a database; end-to-end tests drive the whole system like a user and take seconds to minutes. Each level catches failures the others can't, at a growing cost, so a healthy suite has many unit tests, fewer integration tests and a handful of end-to-end ones.

The Three Levels

Level Scope Speed Example
Unit a function, method or class, dependencies replaced milliseconds a model rejects an invalid ISBN
Integration several real components together tens of milliseconds to seconds GET /api/books/ through FastAPI's TestClient returns 200 and the seeded books
End-to-end the full stack through the UI seconds to minutes a browser logs in and checks out (Rails system specs with Capybara, Playwright)

FastAPI's TestClient (built on HTTPX) calls the app in memory without starting a server: routing, dependency injection and handlers run for real, so it sits at the integration level while staying fast.

Keep Unit Tests Off the Database

Test data factories usually offer both: FactoryBot's build(:user) makes an object in memory, create(:user) saves it. Use build when the test doesn't need a row: no database round trip, no cleanup.

Test-Driven Development

TDD reverses the order: write a failing test for the next small behaviour, write just enough code to pass, then refactor with the tests as a safety net (red, green, refactor). The tests then describe what the code is for, and nothing gets written that no test needs.

References

Review cards

Flashcard Why might a test that uses `create(:user)` be slower than one that uses `build(:user)`?

Using create(:user) involves a database round trip, which is slower than build(:user), which works in memory.

Flashcard What is the main advantage of using FastAPI's `TestClient` for integration tests?

It allows routing, dependency injection, and handlers to run for real without starting a server, making it fast yet still an integration test.

Flashcard What does the 'red, green, refactor' cycle in TDD refer to?

It refers to the process of writing a failing test (red), making the test pass with minimal code (green), and then refactoring the code without breaking the tests.