Behat and HTTP Auth (and Goutte)

So I’ve been trying out Behat for some REST testing recently and came across an interesting situation – I needed to send HTTP Auth credentials as a part of my test. Of course, there’s a method for this on the Session object (setBasicAuth) but it’s not implemented as a default phrase. It took me a bit to make it to the (now logcial) point that I needed to set these before I used the “Given I am on…” phrase to go to the page.

So, to accomplish this, I set up a custom “Given” phrase to set them: “Given that I log in with ‘username’ and ‘password'” so that my full Scenario looks like:
[php]
Scenario: Get the main Index view
Given that I log in with "myuser" and "mypass"
And I am on "/index/view"
Then the response should contain "TextFromPageTitle"
[/php]

And the code is super simple:

[php]
/**
* Features context.
*/
class FeatureContext extends BehatMinkBehatContextMinkContext
{
/**
* @Given /^that I log in with "([^"]*)" and "([^"]*)"$/
*/
public function thatILogInWithAnd($username, $password)
{
$this->getSession()->setBasicAuth($username,$password);
}
}
[/php]

Hope this helps someone else out there trying to send HTTP Auth pre-connection. I’m sure there’s probably an easier way that I’m missing, but this seemed the simplest to me.

7 comments

  1. Hi Chris,

    thanx for this post… is it possible for you to share more things about behat and your REST testing? Maybe I want to use behat and a REST-system, but I can’t figure out how to use it the right way. So it is your chance to bring me into the right direction;-)

    Regards
    Michael

    Like

    1. @michael Definitely…it’s a part of a project for work, so I plan on sharing things as I go along. One of the next things on my list is to figure out Javascript interactions.

      Like

  2. The following solution uses hooks without additional steps.

    This is useful if the authentication is not part of the domain logic, but only meant to protect the test server from public access.

    /**
    * If the website is access protected with HTTP basic auth,
    * we perform an authentication before each scenario with the credentials
    * from the configuration
    *
    * @BeforeScenario
    */
    public function performBasicHttpAuthentication(ScenarioEvent $event) {
    $this->getSession()->setBasicAuth(
    $this->parameters[‘authentication’][‘username’],
    $this->parameters[‘authentication’][‘password’]
    );
    }

    Credentials are stored in context parameters in behat.yml and $this->parameters is set in the constructor.

    Like

Leave a comment