Search code examples
phpunit-testingbehatacceptance-testing

How to check header status code for multiple pages in Behat?


Lets say I have a few page slugs in the database which I would like to check with Behat if the pages are returning header status code 200.

This means I want to have one test(feature) which will check multiple pages, however I'm struggling in how to do this.

Right now I'm using something like this:

Given I am on any page, I should get header status code 200

Which starts one function and every logic is inside that function.

But ideally, I want something like this:

Given I go through all pages
When I check the header status for each page
Then I should get header status code 200

Is there a way to do this?

Note: I use a FeatureContext class and I tried storing e.g. all pages in a private variable, and then tried to access it in the next step of the feature, but that doesn't seem to be working.


Solution

  • For a single page, it is done like this.

    Example Scenario:

      Scenario: Request and Response for single page
        Given I am on "/homepage"
        When I send a GET request to "/cars/list_all"
        And the response status code should be 200
    

    Example Context file: You need to add method below.

    class FeatureContext extends MinkContext implements KernelAwareInterface
    {
        /**
         * @When /^I send a ([^"]*) request to "([^"]*)"$/
         */
        public function iSendARequestTo($method, $url)
        {
            $client = $this->getSession()->getDriver()->getClient();
            $client->request($method, $url);
        }
    }
    

    MinkContext: This already exists so you won't touch it.

    class MinkContext extends RawMinkContext implements TranslatedContextInterface
    {
        /**
         * Checks, that current page response status is equal to specified.
         *
         * @Then /^the response status code should be (?P<code>\d+)$/
         */
        public function assertResponseStatus($code)
        {
            $this->assertSession()->statusCodeEquals($code);
        }
    }
    

    For multiple pages, you'll use Scenario Outlines.

      Scenario Outline: Request and Response for multiple pages
        Given I am on "/homepage"
        When I send a <method> request to <end-point>
        And the response status code should be <response-code>
    
      Examples:
        | method | end-point     | response-code |
        | POST   | /api/page-one | 200           |
        | PUT    | /api/page-two | 200           |