11

I use the FacebookBundle to authenticate users in my Symfony2 application. However, I would like to create functional tests with phpunit which uses an authenticated user.

Moreover, I don't want to use a facebook user for this, but harcoded one.

Does anybody know how to implement this?

Reuven
  • 3,336
  • 2
  • 23
  • 29

1 Answers1

16

It's actually quite simple.

  1. Setup security.yml for test environment (it's a snippet from Symfony 2.0-RC3)

    security:
        encoders:
            Symfony\Component\Security\Core\User\User: plaintext
    
        providers:
            in_memory:
                users:
                    user:  { password: userpass, roles: [ 'ROLE_USER' ] }
                    admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] }
    
        firewalls:
             secured-area:
                 pattern:    ^/demo/secured/
                 http_basic:
                     realm: "Secured Demo Area"
    
  2. As you can see there is HTTP Authentication defined. So now, all you have to do is to setup a client in functional test:

    $client = static::createClient(array(), array(
        'PHP_AUTH_USER' => 'user',
        'PHP_AUTH_PW'   => 'userpass',
    ));
    

This link might be useful: http://symfony.com/doc/current/testing.html

Cliff Edge
  • 143
  • 1
  • 8
Crozin
  • 43,890
  • 13
  • 88
  • 135
  • 2
    Thanks for your answer. However, I want this user to have a lot of other property which are used in my application. For instance, they have a $facebookId property. How can I use hardcoded users with custom properties ? – Reuven Jun 30 '11 at 16:41
  • How do you specify a different security config for the test environment? I'd love to be able to change my cusom wsse proviver to basic in memory. – greg Jul 18 '12 at 18:05
  • @whistlergreg I believe all you have to do is to override `security` definition in `config_test.yml/.xml`. – Crozin Jul 18 '12 at 18:17
  • 1
    tried that, i get `You are not allowed to define new elements for path "security.providers". Please define all elements for this path in one config file.` – greg Jul 18 '12 at 18:18
  • 3
    @whistlergreg Then move import of `security.yml` from `config.yml` to `config_prod/dev.yml`, create `security_test.yml` and import it in `config_test.yml`. You might also need to remove a dependency for `config_dev.yml` from `config_test.yml`. – Crozin Jul 18 '12 at 22:05