A retrieval-augmented generation (RAG) system has two parts that fail in different ways: a retriever that finds passages, and a model that writes an answer from them. If you only look at the final answer, every problem looks like "the AI got it wrong", and you end up tuning prompts to fix what is really a search problem. Good RAG testing measures the two halves separately.
Start with an evaluation set, not a tool
Every useful RAG test starts with a set of questions where you know what a good answer looks like. For each question, record:
- the question, phrased the way real users phrase it (typos and vague wording included);
- the document IDs or passages that should be retrieved;
- the key facts a correct answer must contain, rather than one exact reference answer;
- a tag for the category: simple lookup, multi-document, comparison, out of scope.
Sources for questions: support tickets, search logs, the questions your sales team keeps answering, and every bug report about a wrong answer. Fifty to a hundred well-chosen questions catch far more than a thousand synthetic ones. Synthetic generation is useful to widen coverage later, but a person should review what goes in.
Include questions the system should not answer: topics outside your documents, or questions where the documents disagree. A RAG system that confidently answers everything is not working.
Test retrieval on its own
Run only the retriever over the evaluation set and compare what it returns with the passages you marked as relevant. Two numbers cover most of what you need:
- Recall at k: of the passages needed to answer, how many appear in the top k results. If the right passage is not retrieved, no prompt will save the answer.
- Precision or rank (for example mean reciprocal rank): how high the relevant passages sit. Irrelevant passages near the top distract the model and cost tokens.
These checks are deterministic, cheap and fast, so they can run on every pull request. They are also what tells you whether a change of embedding model, chunk size or hybrid search weighting actually helped. Most "the model hallucinated" reports we investigate turn out to be retrieval misses.
Then test the answer against the context
With retrieval measured, score the generated answer. The useful questions are:
- Groundedness (faithfulness): is every claim in the answer supported by the retrieved passages? This is the direct measure of hallucination.
- Completeness: does the answer contain the key facts from your evaluation set?
- Relevance: does it answer the question asked, or a nearby one?
- Refusal behaviour: for out-of-scope questions, does it say it does not know?
Groundedness and relevance are usually scored by a second model with a strict rubric (an "LLM judge"). Libraries such as Ragas and DeepEval provide ready-made metrics for this. Judges are not perfect, so calibrate them: score 30 to 50 answers by hand, compare with the judge, and adjust the rubric until they agree. Re-check that agreement whenever you change the judge model.
Check citations mechanically
If your product shows sources, test them with code, not with a judge. For each answer, verify that every cited document ID was actually in the retrieved set, that the quoted text exists in that document, and that links resolve. A citation pointing at a document the model never saw is a hallucination with a footnote, and it destroys user trust faster than a vague answer.
Watch the data, not only the code
RAG quality changes when documents change, even if no code does. A re-indexing job with a new chunking setting, a batch of scanned PDFs with bad text extraction, or a duplicated knowledge base can each drop quality overnight. Run the retrieval checks after every re-index, not just after deploys, and keep a few questions whose answers depend on recently added documents.
Wire it into CI with thresholds
A practical setup has two tiers:
- On every pull request: retrieval metrics and citation checks over the full set, plus generation metrics on a small smoke subset. Minutes, not hours.
- Nightly and before release: the full generation evaluation with the judge, compared with the last released version.
Gate on thresholds and on regressions ("groundedness must not drop more than two points against main"), not on exact output. Store every run's scores so you can see trends. We cover the CI side in more detail in running LLM evals in CI.
A minimal example
A retrieval check in Pytest needs nothing beyond your own retriever:
import json, pytest
from app.search import retrieve # your retriever
CASES = [json.loads(l) for l in open("evals/rag_cases.jsonl")]
@pytest.mark.parametrize("case", CASES, ids=lambda c: c["id"])
def test_relevant_passage_is_retrieved(case):
hits = [h.doc_id for h in retrieve(case["question"], k=5)]
assert set(case["expected_docs"]) & set(hits), (
f"none of {case['expected_docs']} in top 5: {hits}"
)Start there, report recall as a percentage across the set, and add generation scoring once retrieval is stable.
Common mistakes
- Only testing the happy path: no out-of-scope, ambiguous or contradictory questions.
- Comparing answers to one reference text with string similarity. Score facts, not wording.
- Trusting an uncalibrated LLM judge as ground truth.
- Evaluating once before launch and never again, while the documents keep changing.
RAG testing is one part of our LLM, RAG and AI agent testing work. If your system also takes actions, read how to test AI agents next.