Behat / Symfony 3 - 如何检查用户是否已登录

时间:2017-03-03 15:56:48

标签: php symfony behat

我正在使用behat和Symfony 3,我想创建一个上下文来检查用户是否已登录,如下所示:

public function __construct(
        UserManagerInterface $userManager,
        AuthorizationCheckerInterface $authorizationChecker,
        TokenStorageInterface $tokenStorage
    ) {
        $this->userManager = $userManager;
        $this->authorizationChecker = $authorizationChecker;
        $this->tokenStorage = $tokenStorage;
    }

/**
     * @param string $user
     * @param string $role
     *
     * @Then /^I should be login as "([^"]*)" with the role "([^"]*)"$/
     */
    public function iShouldBeLoggedInAsWithTheRole(string $user, string $role): void
    {
        $loggedUser = $this->tokenStorage->getToken()->getUsername();
        var_dump($loggedUser);

        Assert::same(
            $loggedUser,
            $user,
            "The logged user is $loggedUser, expected $user"
        );

        Assert::true(
            $this->authorizationChecker->isGranted($role),
            "The user $user must have the role $role"
        );
    }

这些是步骤。第一个失败,运行我在上下文中定义的步骤。第二个工作,步骤进入用户配置文件页面,并检查用户的电子邮件是否在页面中,如果。 只有在正确完成登录后才会发生这种情况。 所以问题似乎是用户上下文中的令牌存储,任何想法为什么会发生这种情况?

Scenario: Log in with username and password
    Given I am on "/login"
    When I fill in the following:
      | username | jsmith@domain.com |
      | password | 1234              |
    And I press "_submit"
    And I am on "/"
    Then I should be login as "jsmith@domain.com" with the role "ROLE_USER"
      The logged user is anon., expected jsmith@domain.com (InvalidArgumentException)

  Scenario: Log in with username and password
    Given I am on "/login"
    When I fill in the following:
      | username | jsmith@domain.com |
      | password | 1234              |
    And I press "_submit"
    And I am on "/profile"
    Then I should see "jsmith@domain.com"

这就是behat配置

default:
    formatters:
        pretty:
            verbose: true
            paths: false
            snippets: false

    extensions:

        Behat\MinkExtension:
               base_url: 'https://localhost/app_dev.php/'
               sessions:
                  default:
                      symfony2: ~

        Behat\Symfony2Extension:
            kernel:
                env: test
                debug: true

        FriendsOfBehat\CrossContainerExtension: ~

        FriendsOfBehat\PerformanceExtension: ~

        FriendsOfBehat\VariadicExtension: ~

    gherkin:
        filters:
            tags: "~@todo && ~@cli" # CLI is excluded as it registers an error handler that mutes fatal errors

1 个答案:

答案 0 :(得分:0)

您正在登录“模拟浏览器页面”

Given I am on "/login"
  When I fill in the following:
    | username | jsmith@domain.com |
    | password | 1234              |
  And I press "_submit"

这是一个完全独立于您尝试检索已登录用户的behat进程的进程。

你唯一可以做的就是重新定义登录步骤,明确查询数据库,保存在shared context这些用户中,并在之后检查(但此时,此测试,似乎是很无用)