How to write a functional test with user authentication?

I am writing a functional test for a page that requires user authentication. I am using the sfDoctrineGuard plugin.

How do I authenticate a user in my test?

Do I need to enter each test through the login screen?

Here is my wrong code:

$b->post('/sfGuardAuth/signin', array('signin[password]' => 'password', 'signin[username]' => 'user', 'signin[_csrf_token]' => '7bd809388ed8bf763fc5fccc255d042e'))-> with('response')->begin()-> checkElement('h2', 'Welcome Humans')-> end() 

thanks

+4
source share
2 answers

Yes, you need to log in to run the tests. Fortunately, this is much simpler than the method described above. See the β€œBetter and Easier Way” in this blog post .

You can make the signin method part of any TestFunctional class according to how you structure your tests.

+3
source

The difficult role is that the test browser destroys the context object before each request (see sfBrowser :: call () ).

You can authenticate the user by introducing a listener that will call the user method signIn() when the context.load_factories event fires during context initialization:

 function signin( sfEvent $event ) { /* @var $user sfGuardSecurityUser */ if( ! $user = $event->getSubject()->getUser() ) { throw new RuntimeException('User object not created.'); } if( ! $user instanceof sfGuardSecurityUser ) { throw new LogicException(sprintf( 'Cannot log in %s; sfGuardSecurityUser expected.', get_class($user) )); } if( $user->isAuthenticated() ) { $user->signOut(); } /* Magic happens here: */ $user->signIn($desired_user_to_log_in_as); $event->getSubject()->getEventDispatcher()->notify(new sfEvent( $this, 'application.log', array(sprintf('User is logged in as "%s".', $user->getUsername())) )); } /* Set signin() to fire when the browser inits the context for subsequent * requests. */ $b->addListener('context.load_factories', 'signin'); 

This will cause the browser to log in to all subsequent requests. Note that sfBrowser does not have a removeListener() method.

Adapted from sfJwtPhpUnitPlugin (FD: I am the lead developer for this project).

+6
source

All Articles