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:

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"

And the code is super simple:

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

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.

Category: Behat, PHP, Testing 5 comments »

5 Responses to “Behat and HTTP Auth (and Goutte)”

  1. everzet

    It’s the correct and best way ;-)

  2. Shashikant

    Great. It would be better if implemented with Selenium, Webdriver or Sahi.

  3. Michael

    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

  4. enygma

    @shashikant do you have an example of the implementation in these other drivers? I’m pretty new to the Behat game…

  5. enygma

    @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.


Leave a Reply



Back to top