The questions that come up, with what is going on and what to do.

“message key x.title is not defined for lang cy”

The expectation resolved its key in the page’s language and the language has no such key. Either the translation is missing, which is the finding, or the words were never meant to be a message key, in which case use the …Text form or literal("...").

“2 elements matched, so this assertion is ambiguous”

An expectation that names one element found several. The page really has two inputs with that name, or two elements with that id, which is itself a defect the unique-ids rule would report. Where several matches are legitimate, assert on the group: cssSelector(".govuk-summary-list__row") and elementCount(".govuk-summary-list__row", 4).

“no element with role button announces this name”

The element exists but its accessible name is not what the spec expects. The finding lists the names that are announced, which usually shows the problem: a <button> whose text comes from a message key the template did not resolve, or a name that comes from an aria-label you had forgotten about. An element with an explicit role is matched only by that role, so <a role="button"> is not found by role("link").

“field has no associated label”

The expectation found no <label for="..."> matching the field’s id. It asks for that label itself, so an aria-label or aria-labelledby on the field does not satisfy it, and neither does a <label> wrapped around the field without for. A text input with no id reports “field has no id, so no label[for] can name it” instead. The GOV.UK components produce the label; a hand-written <input> needs one. The one field of a fieldset labelled by its legend can say so with labelledByLegend.

“the hint is not announced with the field”

The hint text is right but the control’s aria-describedby does not reference the hint’s id, so a screen reader never reads it. govukInput and govukRadios wire this up when you pass hint; a hand-rolled hint does not.

A rule fires on a component that has no layout

Rules about titles, landmarks and metadata are page-level and stay silent for a fragment, which is anything that does not start with a doctype or <html>. If a component spec sees them, the component is being rendered inside a layout, or the fragment starts with <html> itself.

The application will not start

TwirlSpec builds a GuiceApplicationBuilder application with metrics, auditing and the CSP nonce switched off. A service whose modules need more configuration at start-up provides it through applicationConfig, the same way it declares its languages. A NoClassDefFoundError for a Play class means one of play, play-test or play-guice is missing from the test classpath: the library declares them Provided so that it never moves your Play version, and your project supplies them.

The application needs a database it cannot reach

A service built on HMRC’s bootstrap instantiates every controller when the application starts, and the PlayMongoComponent from hmrc-mongo pings the database as it is built, with a five-second timeout that fails the start. The service’s own GuiceOneAppPerSuite specs need a running Mongo for the same reason, so running one is the usual answer.

Without one, swap the component for a stub. TwirlSpec builds its application from configuration alone, and a module can be named there:

package specs

import com.google.inject.AbstractModule
import org.mongodb.scala.{MongoClient, MongoDatabase}
import play.api.{Configuration, Environment}
import uk.gov.hmrc.mongo.MongoComponent

import scala.concurrent.duration.{DurationInt, FiniteDuration}

object NoMongo extends MongoComponent {
  lazy val client: MongoClient     = MongoClient("mongodb://localhost:27017/specs")
  lazy val database: MongoDatabase = client.getDatabase("specs")
  val initTimeout: FiniteDuration  = 1.second
}

class NoMongoModule extends AbstractModule {
  override def configure(): Unit = bind(classOf[MongoComponent]).toInstance(NoMongo)
}

object NoMongoApplication {
  // the service's own module list, with hmrc-mongo's module swapped for the stub;
  // one stable value, so every suite shares one application
  val config: Map[String, Any] = {
    val base = Configuration.load(Environment.simple())
    Map(
      "play.modules.enabled"  -> (base.get[Seq[String]]("play.modules.enabled") :+ "specs.NoMongoModule"),
      "play.modules.disabled" -> (base.get[Seq[String]]("play.modules.disabled") :+ "uk.gov.hmrc.mongo.play.PlayMongoModule")
    )
  }
}
override def applicationConfig: Map[String, Any] = NoMongoApplication.config

Two things make this work. The driver connects only on first use, so the stub builds without a database. And each repository awaits its index creation for initTimeout, logging a plain timeout as a warning and throwing on any other failure, so the timeout has to arrive first: keep the driver’s server selection timeout at its default rather than shortening it in the URI. A spec base with an application of its own gives the builder .disable[PlayMongoModule].overrides(bind[MongoComponent].toInstance(NoMongo)) instead.

Specs are slow to start

The first spec in a JVM boots a Play application. Every later spec with an equal applicationConfig shares it, whether or not it is the same map, so a spec base that overrides applicationConfig should keep the values stable: a random port or a timestamp in it means a new application per suite. SharedApplication.instanceCount says how many have been built, and a service that suspects it is still booting per spec can assert on it.

Specs run in parallel

They can. The shared application is built once per configuration and never stopped until the JVM exits, and the coverage record is keyed by spec, so suites running side by side do not interfere.

“cy is not a configured language”

inLanguage(Lang("cy")) and renderIn(Lang("cy")) render in Welsh only when cy is among the configured languages. Play would otherwise answer with the first configured language, and a Welsh spec would pass on the English page, so the library fails instead. TwirlSpec takes the languages from play.i18n.langs in the service’s conf/application.conf; declare Welsh there, or through applicationConfig on the spec base.

“No CSRF token was generated for this request”

TwirlSpec’s request carries a CSRF token whenever play-filters-helpers is on the classpath, as it is in any application built with the Play sbt plugin. So this comes either from a request the spec built itself, usually a fakeRequest on a spec base that uses TwirlSpecDsl, or from a project without that library. A project without it adds it first:

libraryDependencies += "org.playframework" %% "play-filters-helpers" % play.core.PlayVersion.current % Test

A spec that builds its own request then gives it a token:

implicit val fakeRequest: Request[AnyContentAsEmpty.type] =
  CSRFTokenHelper.addCSRFToken(FakeRequest("GET", "/"))

formWithCSRF from play-frontend-hmrc does not throw; it leaves the token field out, so a spec without a token renders a form a citizen never sees.

A view needs an implicit the spec does not have

TwirlSpec provides messages, request (with the language cookie and, where play-filters-helpers is present, a CSRF token) and messagesApi. Anything else a view takes implicitly, such as an AppConfig, the spec provides:

implicit val appConfig: AppConfig = inject[AppConfig]

Warnings appear in the test output but nothing fails

That is by design. Warning rules and .asWarning expectations are reported through ScalaTest’s alerts on a green run, so a service can see what failOnWarnings = true would start failing. reportWarnings = false silences them on passing tests.

assertEverything reports things the layout put there

Set coverageScope to the part of the page the view spec answers for, "main, #main-content" by default, and list what every page inherits in coverageIgnored, by id, or coverageIgnoredSelectors. Ignoring a wrapper ignores what it holds.

The template scan reports an element that is fine

TagBalance.checkTemplate reads the template’s literal markup. An element opened in one branch of an @if and closed in the other looks unbalanced, because on any single render it is; and markup that arrives from a helper is invisible to it. Both are limits of scanning without rendering, and the rendered-page rule tags-are-balanced sees the truth.

Seeing what the library did

The library traces its work at DEBUG through Play’s logger, under the name io.github.frikit.twirlspec: the application it built and with which settings, each page it rendered, each check and the rules it failed, and each coverage or language comparison. The logback configuration the service’s tests use governs it, so one line in logback-test.xml turns it on:

<logger name="io.github.frikit.twirlspec" level="DEBUG"/>

Something else

The README lists every expectation, matcher and rule. If the library does something surprising that these pages do not explain, an issue with the template and the spec that shows it is welcome.