In lesson 3, I mentioned that the current code has some gaps.
We checked the expected nodes were shown but not the opposite - the nodes we didn't expect to see weren't shown.
Let's fix that in this lesson.
## Only returning published nodes
First, let's ensure that only published nodes are returned and displayed on the page.
We can do this easily with a functional test, so add a new test method to `BlogPostTest`:
```php
public function testOnlyPublishedNodesAreShown(): void {
PostBuilder::create()
->setTitle('Post one')
->isPublished()
->getPost();
PostBuilder::create()
->setTitle('Post two')
->isNotPublished()
->getPost();
PostBuilder::create()
->setTitle('Post three')
->isPublished()
->getPost();
$this->drupalGet('/blog');
$assert = $this->assertSession();
$assert->pageTextContains('Post one');
$assert->pageTextNotContains('Post two');
$assert->pageTextContains('Post three');
}
```
Import the `PostBuilder` by adding `use Drupal\atdc\Builder\PostBuilder;` if needed, and run the test to see the first error:
> Error: Call to undefined method Drupal\atdc\Builder\PostBuilder::isPublished()
In this test, we want to create some published and unpublished posts and assert only the published ones are shown, but we don't have this functionality on the `PostBuilder`.
To fix the error, add this function so it exists:
```php
public function isPublished(): self {
return $this;
}
```
We'll revisit this later once we have a failing test that requires further changes.
Running the tests again, you should get this unexpected error:
When using `PostBuilder` in the previous lesson, we were always providing a created date, but, as we're not doing that in this test, the created date is `NULL`, causing this error.
Update the `getPost()` method to only set the created time if the `created` property has a value.
$assert->pageTextNotContains('This is not a post');
}
```
Use `PostBuilder` to create two posts and `$this->createNode()` to create a post of a different type.
In this test, we want the two post titles to be shown but not the page's title.
If you run the test, it should fail as expected:
> The text "This is not a post" appears in the text of this page, but it should not.
Now we have a failing test, let's add the extra condition to `PostNodeRepository`:
```php
$nodes = $nodeStorage->loadByProperties([
'status' => TRUE,
'type' => 'post',
]);
```
With both conditions, both tests should now pass, and you should only see published node articles on your blog page.
## Conclusion
With these changes, the `PostNodeRepository` is more robust and fully featured.
While we could also write new Kernel tests for this functionality, it's already covered in the Functional tests. If you write accompanying Kernel tests, you wouldn't be able to make them fail without also making the Functional tests fail.