首次登录后,每次都防止用户登录方法运行

时间:2014-10-17 13:01:43

标签: symfony selenium behat mink

我试图找到一种方法来创建一个会话/ cookie来处理用户登录,这样下面的方法就不会在每个单一时间对数据库进行查询。它几乎在所有场景中被调用,并且大大减慢了测试套件的速度。

重要说明:有2个不同的用户登录:用户和管理员,因此可能会有三个不同的会话。

When I login as "user"
When I login as "admin"

class FeatureContext extends MinkContext implements KernelAwareInterface
{
    /**
     * @When /^I login as "([^"]*)"$/
     *
     * @param $type User role type.
     */
    public function iLoginAs($type)
    {
        $userData['user']  = array('username' => 'you', 'password' => '111');
        $userData['admin'] = array('username' => 'mee', 'password' => '222');

        $this->visit('/login');
        $this->fillField('username', $userData[$type]['username']);
        $this->fillField('password', $userData[$type]['password']);
        $this->pressButton('_submit');
    }
}

1 个答案:

答案 0 :(得分:0)

这里最大的问题来自于您向服务器发送实际请求,Beaw和您的应用程序都会处理这些请求。相反,你可以将这个逻辑带入你的上下文,并在Behat 3中这样做:

Given I am logged in as "…"

class MinkContext extends \Behat\MinkExtension\Context\MinkContext
{

    /**
     * @Given /(?:|I am )logged in as "(?P<type>\d+)"/
     */ 
    public login($type)
    {
        // Here goes the same logic as per your login action: load the user details, create 
        // session, etc. In theory you can store the signed in user model or session id in a
        // static property and don't load it every time the step is invoked.
    }

    /**
     * @beforeStep
     *
     * @param BeforeStepScope $scope
     */
    public function synchroniseClientSession(BeforeStepScope $scope)
    {

        // Setup session id and Xdebug cookies to synchronise / enable both.

        $driver = $this->getSession()->getDriver();

        // Cookies must be set per a specific domain + Chrome might start with a weird url.

        if ($driver instanceof Selenium2Driver && $driver->getCurrentUrl() === 'data:,') {
            $driver->visit($this->getMinkParameter('base_url'));
        }

        $driver->setCookie(session_name(), session_id());
        $driver->setCookie('XDEBUG_SESSION', 'PHPSTORM'); // Can also do that to enable debugging…
    }
} 

如果您了解会话在服务器和客户端之间如何工作和传递,那么这一切都非常简单。你基本上是在你的上下文中“手动”完成它,但这个想法与控制器/动作中发生的事情完全相同。

login开始新会话之前,您需要确保没有会话打开,在那里您可能遇到一些令人讨厌的问题,但希望不会。

相关问题