Adopting in an existing service
Most Play services already have view specs, and most of those share the same
shape: a ViewSpecBase that boots an application and provides messages, a
ViewBehaviours trait with normalPage, pageWithBackLink,
pageWithSubmitButton and friends, and a spec per view that calls them. The
library replaces that scaffolding, and can do so gradually.
A spec base to replace the old one
package views
import io.github.frikit.twirlspec.{HmrcServiceChecks, TwirlSpec}
import io.github.frikit.twirlspec.messages.MessagesIntegrity
import org.scalatest.matchers.must.Matchers
import org.scalatest.wordspec.AnyWordSpec
// every rule, less the search-result ones a GOV.UK service has no use for,
// with what every service on play-frontend-hmrc would otherwise write here
trait ViewSpecBase extends AnyWordSpec with Matchers with TwirlSpec with HmrcServiceChecks {
// the languages come from play.i18n.langs in conf/application.conf
// the service is bilingual, so the message files must be too
override def messagesIntegrityConfig = MessagesIntegrity.Config(requireTranslations = true)
// the furniture every page must carry
val furniture = expectations(serviceName(), languageToggle, signOutLink, timeoutDialog)
}
A view spec then reads like the page:
import play.api.i18n.Lang
class WhatIsYourNameViewSpec extends ViewSpecBase {
private val view = inject[WhatIsYourNameView]
private val form = inject[WhatIsYourNameFormProvider].apply()
"WhatIsYourNameView" should {
"render the question" in {
render(view(form)) must display(
furniture,
title("whatIsYourName.title"),
heading("whatIsYourName.heading"),
backLink,
textInput("value").labelled("whatIsYourName.heading"),
submitButton(),
noErrors
)
}
"render in Welsh" in inLanguage(Lang("cy")) {
render(view(form)) must display(title("whatIsYourName.title"), heading("whatIsYourName.heading"))
}
"have been asserted in full" in {
render(view(form)) must assertEverything
}
}
}
HmrcServiceChecks leaves play-frontend-hmrc’s report-a-problem link out of
coverage, and lets “HMRC” read the same in every language. A service on another
layout mixes in GovukServiceChecks and lists what that layout gives every page
in coverageIgnored, by id, or coverageIgnoredSelectors.
A table of pages
Much of what an old ViewBehaviours does is the same for every page: the
standards in every language, blank and with errors, and the same thing said in
each language. PageCatalogue, in twirl-spec-all, makes that a table, and
leaves a spec per view for what is particular to it:
import io.github.frikit.twirlspec.PageCatalogue
class EveryPageSpec extends ViewSpecBase with PageCatalogue {
catalogue(
staticPage("Info")(inject[InfoView](draftId, index)),
formPage("Name", nameForm)(inject[NameView](_, draftId)),
formPage("Date of birth", dobForm, "part of a date" -> Map("value.day" -> "1"))(
inject[DateOfBirthView](_, draftId)
),
staticPage("Not found")(inject[PageNotFoundView]()).exceptTranslation("i18n-same-links")
)
}
Each page gets a test for each check in each language, named after both: one
for each state rendering in en, one for each rule run on every state in en,
the same in cy, and one for each comparison of cy against en, so the
report says what was checked where, and a failure names the rule. A
form page is rendered blank, with the errors of an empty submission, and with
those of each submission named, and a submission that gives no errors fails its
test. The empty submission is the blank form sent untouched, as a browser sends
it, each control with the value it renders with, and nothing where it cannot
tell which of several forms holds the fields. A spec per view can put its own
tests under the page’s label with cataloguePage(page) { ... }, so the report
names the view once. In a style other than
AnyWordSpec, mix in PageCases and write a test for each of checksOf(page),
or call checkStandards(page) and checkTranslation(page) from tests of your
own.
Keeping an existing application
If the old base already builds an application through GuiceOneAppPerSuite
and every spec depends on its messages, fakeRequest or app, keep it and
mix in TwirlSpecDsl rather than TwirlSpec. The DSL declares no implicits
and builds no application, so nothing clashes:
trait ViewSpecBase extends AnyWordSpec with Matchers with GuiceOneAppPerSuite with TwirlSpecDsl with SuiteLifecycle with GovukServiceChecks {
implicit val messages: Messages = ... // yours, as before
}
render(html) takes the implicit Messages in scope, and render(html, lang,
messages) takes explicit ones for another language. The one thing
TwirlSpecDsl cannot offer is inLanguage and renderInEachLanguage, which
need the application; build the pages for each language yourself and pass
them to translateConsistently.
The request is the spec base’s own too. Most existing spec bases already build
it with withCSRFToken; keep that, because a view that renders
CSRF.formField throws without a token, and formWithCSRF quietly renders a
form with no token field.
Adopting one view at a time
Nothing requires a big bang. Old specs and new ones can share a test source tree, and a new spec can start loose and tighten:
- Mix in
TwirlSpecalone, with no rule trait, and port the old assertions todisplay(...). The oldpageWithBackLinkbecomesbackLink,pageWithSubmitButtonbecomessubmitButton(), andnormalPage(...)becomestitle,headingandserviceName(). - Add
WcagChecks. Fix what it finds in the templates; it is usually labels and error-summary links.meetStandardsExceptanddisplayOnlyare there for the page that genuinely cannot comply yet. - Add the rest of the traits, or
GovukServiceChecks(AllChecksless the search-result rules), orHmrcServiceCheckson play-frontend-hmrc. - Add
assertEverythingas the last test, and delete the assertions the coverage report shows to be redundant. - Add the message-file checks once, in one spec, and
translateConsistentlyto the pages that render in every language.
What changes in a spec base
| Home-grown | twirl-spec |
|---|---|
a copy of ViewSpecBase per service, drifting |
TwirlSpec or TwirlSpecDsl, versioned |
normalPage(view, "x") |
title("x.title"), heading("x.heading") |
pageWithBackLink(view) |
backLink, or backLink.to(url) |
pageWithSubmitButton(view, "Continue") |
submitButton() |
pageWithHint(view, "x.hint") |
textInput("value").hinted("x.hint"), which also checks it is announced |
doc.select("#value").attr("value") |
formValues("value" -> "Ada") or textInput("value").withValue("Ada") |
doc.title mustBe messages("x.title") |
title("x.title"), which reports an undefined key instead of passing on it |
| nothing | noErrors, errorSummary(...), assertEverything, every rule |
Moving from 2.x to 3.x
3.0.0 draws a line under 2.x and starts the stable line from 2.15.0’s code: the same API, rule ids, published dependencies and verdicts. A service on 2.15.0 changes its version and nothing else. One on an earlier 2.x meets what the releases between changed, chiefly in the page catalogue: from 2.12.0 it names a test after each check, and from 2.14.0 after each language as well, so a test filter on the old names matches nothing. Each release’s notes, on its GitHub Release, say what it changed.
Moving from 1.x to 2.x
2.0.0 is published for Scala 3 only, on the 3.3 LTS line. On Scala 3, the API
is source-compatible with 1.0.x, with one exception: new HtmlStandards(...)
takes its attribute prefixes explicitly, and the HtmlStandards object remains
the set with none. Play 3.0.0 is now the floor rather than 3.0.11, so a service
on any 3.0.x resolves the artifacts without upgrading Play.
A service on Scala 2.13 cannot use 2.x or 3.x, and 1.0.0 is not a place to adopt in
the meantime. It is historical and receives no fixes: it still reports
rel="noreferrer", tabindex="-1" and maximum-scale=10 as problems when
they are not, misses a password field in a form that names no method, names a
control differently from rule to rule, and renders a bilingual service’s Welsh
specs in English. Adopt 3.x as part of the service’s move to Scala 3, which
touches the build anyway.
Moving from a 0.x snapshot
Nothing before 1.0.0 was published, but a service that built a snapshot
locally will find three renames: the rule sets moved from the standards
package into the package of the module that owns them (wcag, govuk,
quality); welsh and inWelsh became configuration, inLanguage(Lang("cy"))
with play.i18n.langs declared; and the messages module’s Config speaks of
a base language and translations rather than English and Welsh
(requireWelsh is requireTranslations, englishMessages is
baseMessages).