Basic

Selecting from the served document

grep proves a string exists, which is weaker than proving an element exists at a place. The step up is to parse the document and select by structure, so the assertion is about the tree rather than about bytes.

What you will see

The assertion compares two numbers. A missing card fails here, not on a presence check.

About 1 min of reading

Try It

Select and count instead of grepping

1

Fetch the page

curl -s http://localhost:3000/tutorials/lessons -o /tmp/p.html

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The document on disk for the next step to parse.
2

Count the cards structurally

grep -oE 'class="tutorial-card' /tmp/p.html | wc -l

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The number of cards rendered. Compare it to the catalogue count, not to zero.
3

Read the hrefs

grep -oE 'href="/tutorials/[a-z0-9-]+' /tmp/p.html | sed 's|href="/||' | sort -u | wc -l

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The distinct tutorial links. A duplicate link collapses here, which is the bug to catch.
4

Assert the count matches

printf 'want=33\ngot=%s\n[ "$want" = "$got" ] || { echo "FAIL count"; exit 1; }\n' "$(grep -oE 'class="tutorial-card' /tmp/p.html | wc -l)" | tee -a t3.sh

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The assertion compares two numbers. A missing card fails here, not on a presence check.
Do not assert a count that includes hidden or off-page items. Count what the page renders and nothing else.

Data Flow

Bytes to a tree
1 Receive the document
↓
2 Parse to a tree
↓
3 Select by structure
↓
4 Assert on the selection
Why this works
The minimum structure to assert

Element exists, has the expected attribute, and the attribute value is one of the allowed set. Those three cover most markup bugs.

When grep is enough

For a single stable marker in a small page. The moment the assertion needs a place or a count, switch to a parser.

Examples

String versus element

The text can appear in an attribute or a comment while the element the test wants is missing. A structural selection cannot be satisfied by the wrong place.

Select, then count

Select the cards and count them. A count assertion catches the empty list, which a presence assertion misses because one card still satisfies it.

Select the attribute, not the line

Read the href of a link rather than the line containing it. Attribute order and quoting changes then stop breaking the test.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← A fetch test: request, status, body
Previous Lesson
A fetch test: request, status, body
Next Lesson
Testing that links go where they should
Testing that links go where they should →