Writing assertions first

As well as writing comments first, when writing tests, I sometimes like to write my tests backwards and start by writing the assertions first.

I know what I want to assert in the test, so it's an easy place to start.

I'll run it, see the error, fix it and continue working backwards.

For example, I could start with this:

public function testOnlyPostNodesAreShown(): void {
  $assert = $this->assertSession();
  $assert->pageTextContains('Post one');
  $assert->pageTextContains('Post two');
  $assert->pageTextNotContains('This is not a post');
}

This test will fail when I run it, but it makes me think about what I need to do to fix the error and how to do so in the best way.

In this case, I need to make a request to the page that should render the text:

public function testOnlyPostNodesAreShown(): void {
  $this->drupalGet('/blog');

  $assert = $this->assertSession();
  $assert->pageTextContains('Post one');
  $assert->pageTextContains('Post two');
  $assert->pageTextNotContains('This is not a post');
}

This will still fail, as I also need to create the required posts:

public function testOnlyPostNodesAreShown(): void {
  PostBuilder::create()->setTitle('Post one')->getPost();
  PostBuilder::create()->setTitle('Post two')->getPost();

  $this->createNode([
    'title' => 'This is not a post',
    'type' => 'page',
  ]);

  $this->drupalGet('/blog');

  $assert = $this->assertSession();
  $assert->pageTextContains('Post one');
  $assert->pageTextContains('Post two');
  $assert->pageTextNotContains('This is not a post');
}

Now the test passes.

Doing test-driven development keeps my code clean and minimal, and I find this approach keeps my test clean, too.

- Oliver

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.