Use example.com in your tests

July 11, 2024

Key takeaway: Use reserved names such as example.com for every fake address in tests and docs, so no test data can reach a real person.

Use example.com in your tests and docs, not a domain you made up. Made-up domains usually belong to someone. test.com has been registered since 1997 and acme.com since 1991.

Most fixtures never leave the test process. The trouble starts when the data travels. A seed script loads sample users into staging with real SMTP credentials, and a job sends them all welcome emails. A README tells readers to curl a domain that sounds fake and isn’t. Either way, a stranger gets your traffic.

example.com is run by IANA and publishes a null MX record, so mail to jane@example.com is rejected instead of reaching a person. RFC 2606 reserves it along with example.net, example.org, and the .test, .example, .invalid, and .localhost top-level domains.

Reserved doesn’t mean offline. example.com resolves, so a test that actually requests it still flakes like any network test. Pick the name for the job:

# Placeholder data that should never be contacted
user = User.new(email: "jane@example.com")

# A host that must fail DNS lookup, for testing that error path
client = ApiClient.new(base_url: "https://api.unreachable.invalid")

# A local service you point at 127.0.0.1 in /etc/hosts
client = ApiClient.new(base_url: "http://api.myapp.test:3000")

The same goes for other made-up data. RFC 5737 reserves 192.0.2.0/24, 198.51.100.0/24, and 203.0.113.0/24 for documentation, and RFC 3849 reserves 2001:db8::/32. Phone numbers 555-0100 through 555-0199 are set aside for fiction.

The easy fix is to make the safe value the default, like sequence(:email) { |n| "user#{n}@example.com" } in your FactoryBot factory. Then anyone reading your tests knows at a glance it’s a placeholder.