Search⌘ K
AI Features

A Note on Assertions Per Test

Learn how to manage multiple assertions in Rails model tests effectively. This lesson covers contrasting styles such as one assertion per test and combining assertions, explains the use of RSpec features like has_attributes matcher and :aggregate_failures, and discusses best practices for writing clear, maintainable tests.

We’ll often find that a common setup results in multiple assertions in a test. This is particularly true of integration tests. For example, when we wrote our initial test to add tasks back in Test-Driven Rails, we made several assertions about the project’s existence and its relationship with the tasks we’d just created.

There are two contrasting styles for writing tests with multiple assertions. In one style, the setup and all the assertions are part of the same test. If we were trying to test changes when we mark a task complete, then having all the assertions in the same test might look like this:

Ruby
it "marks a task complete" do
task = tasks(:incomplete)
task.mark_complete
expect(task).to be_complete
expect(task).to be_blocked
expect(task.end_date).to eq(Date.today.to_s(:db))
expect(task.most_recent_log.end_state).to eq("completed")
end

In contrast, we could put each assertion in a separate test and put the common setup in a setup block. Using the same set of assertions in separate tests ...