我在 Symfony2 / Doctrine2 中使用 Behat。现在,我有这种情况归结为“如果我登录并转到 /login,我应该转到 / 而不是”:
@login
Scenario: Go to the login page while being logged in
Given I am logged in
When I go to "/login"
Then I should be on "/"
对于@login,我创建了以下内容:
/**
* @BeforeScenario @login
*/
public function loginUser()
{
$doctrine = $this->getContainer()->get('doctrine');
$userRepository = $doctrine->getRepository('MyTestBundle:User');
$user = $userRepository->find(1); // 1 = id
$token = new UsernamePasswordToken($user, NULL, 'main', $user->getRoles());
$this->getContainer()->get('security.context')->setToken($token);
}
在“当我去 /login”代码(控制器被调用)中,令牌似乎消失了(不是我想要的):
/**
* @Route("/login", name="login")
*/
public function loginAction()
{
$token = $this->get('security.context')->getToken();
$fd = fopen('/tmp/debug.log', 'a');
fwrite($fd, $token);
// prints 'AnonymousToken(user="anon.", authenticated=true, roles="")'
...
但在 FeatureContext 中,它似乎一直存在(我希望它会起作用)。在“鉴于我已登录”中:
/**
* @Given /^I am logged in$/
*/
public function iAmLoggedIn()
{
$token = $this->getContainer()->get('security.context')->getToken();
$fd = fopen('/tmp/debug.log', 'a');
fwrite($fd, $token);
// prints 'UsernamePasswordToken(user="admin", authenticated=true, roles="ROLE_ADMIN")'
...
我这样跑:
app/console -e=test behat
我也在控制器中这样做以确保它是测试:
fwrite($fd, $this->get('kernel')->getEnvironment());
// prints 'test'
任何线索如何验证用户?我将不得不测试很多管理页面,所以如果我可以将登录连接到@BeforeSuite、@BeforeFeature(或@BeforeScenario ...),这样我就不会被阻止。
(也欢迎有关禁用身份验证机制以进行测试的建议,或存根/模拟用户的方法。)