Home / Behat Demo: Blog Search

Testing Blog Search with Behat and Gherkin

The documentation that used to be at this address is no longer published, and its source was never released under an open license, so it is not reproduced here. This page is an independent guide to the same topic, written for this archive. It is not the project's documentation and is not affiliated with its authors.

Behat is a behaviour driven development framework for PHP that reads the same Gherkin syntax as Cucumber. Demo projects for Behat often use a blog because everyone understands the domain: posts, titles, tags and a search box. Search makes a good example feature because it has an obvious happy path and plenty of edge cases.

Example feature

Feature: Blog search
  In order to find articles on a topic
  As a reader
  I need to search the blog

  Background:
    Given the following posts exist:
      | title                        | body                              |
      | Getting started with Behat   | Install Behat and write a feature |
      | Writing good scenarios       | Keep each scenario focused        |
      | Holiday photos               | Pictures from the beach           |

  Scenario: Searching for a word in a title
    When I search for "Behat"
    Then I should see "Getting started with Behat" in the results
    And I should not see "Holiday photos" in the results

  Scenario: Searching for a word that only appears in the body
    When I search for "focused"
    Then I should see "Writing good scenarios" in the results

  Scenario: No matching posts
    When I search for "kubernetes"
    Then I should see "No posts matched your search"

  Scenario: Search is case insensitive
    When I search for "behat"
    Then I should see "Getting started with Behat" in the results

Making it run in Behat

With the Mink extension, many steps such as filling in a field and pressing a button are available out of the box. For readable features, define your own higher level steps like "I search for" in a context class, and implement them using Mink underneath. The table in the Background should be loaded through your application's own data layer so the posts are indexed exactly as real posts would be.

Edge cases worth covering

A note on search engines

If search is backed by a separate index, a newly created post may not be searchable immediately. Make your test setup refresh the index after loading data, rather than adding sleeps to the scenario.

More on Behat Demo: Blog Search

Explore the archive