Ruby on Rails: Overcoming Text Matching Challenges with normalize_ws in Rspec

Nicolás Galdámez
Unagi
Published in
2 min readMar 15, 2024
Freepik Illustration

In Ruby on Rails app testing, accurate text matching is crucial for validating functionality, especially in system tests where you’re testing the app end-to-end. However, differences in whitespace formatting can cause unexpected failures, making tests fragile and hard to maintain 👎.

This article explains how to tackle this issue using the normalize_ws option in system tests with Capybara and RSpec.

Categories

Picture yourself creating a system test for a feature that shows a category group name and a list of categories associated with it.

Example

Because of formatting or content creation, the spacing between words may differ, causing tests to fail if not managed correctly. For example, checking if the title “Category Group 1 > Categories” is displayed could be a problem because of formatting.

Introducing normalize_ws

Fortunately, Capybara offers the normalize_ws option to handle this problem. When activated, normalize_ws standardizes whitespace in both expected and actual text before comparison. This guarantees that differences in whitespace, such as extra spaces or tabs, do not impact the test result.

Let’s explore how to use normalize_ws in a Ruby on Rails system test using Rspec:

# spec/system/category_group_spec.rb 
require 'rails_helper'

RSpec.describe 'Category group', type: :system do
let(:category_group) { FactoryBot.create(:category_group, name:'Technology') }
let(:category) { FactoryBot.create(:category, name: 'Computers', category_group: category_group) }

before do
visit category_group_path(category_group)
end

it 'displays the category group name followed by > Categories' do
expect(page).to have_text("#{category_group.name} > Categories", normalize_ws: true)
end

...
end

In this system test, we visit the category group page and then use Capybara’s have_text matcher with normalize_ws: true to ensure accurate text matching. This means that any differences in whitespace between the expected and actual text will be ignored during comparison.

By using the normalize_ws option in system tests with Capybara and RSpec, we can write more reliable tests that consider whitespace variations in text output. This improves test reliability and maintainability, ultimately enhancing the quality and stability of Ruby on Rails applications. Whether you're testing user interactions, page rendering, or data manipulation, consider including normalize_ws in your system test suite to ensure strong and accurate testing.

Unagi is a software boutique that offers software development services in Ruby on Rails, a stack we still choose after +12 years. Check out more on our social media.

--

--

Nicolás Galdámez
Unagi
Editor for

Co-fundador de @unagi. Me gusta el cine, la lectura, y la ensalada de frutas.