Skip to content
Jeffrey Way edited this page Apr 13, 2015 · 3 revisions

Laravel with Selenium

Writing tests that execute against a running browser, such as when using the Selenium extension, can be tricky. If you extend the Selenium extension, you won't immediately have access to the Laravel application. This means things like the facades, or even TestDummy, won't be available. To remedy this, import the Laracasts\Integrated\Services\Laravel\Application trait. Badabing, badaboom, you're good to go.

use Laracasts\Integrated\Extensions\Selenium;
use Laracasts\Integrated\Services\Laravel\Application as Laravel;

class AuthTest extends Selenium {

    use Laravel;

    /** @test */
    public function it_registers_a_user()
    {
        // Reference any Laravel facades and such...

        $this->visit('auth/register')->andDump();
    }

Just remember that, unlike the Laravel extension, in this case you'll have two instances of the Laravel app running. This can be a little confusing. For instance, if you try to login a user before the tests run...

Auth::loginUsingId(id);

$this->visit('/page');

...well that won't work like you expect. Selenium is opening a browser and visiting your app for the first time. It won't be using the instance of Laravel that you've loaded from your tests. Make sense? So keep that in mind. Just use the app in your tests to do basic things, like fetching config, manipulating the database, etc.

Database Transactions

If you're using the Laravel extension of this package, then you may also pull in a trait, which automatically sets up database transactions. By including this trait, after each test completes, your database will be "rolled back" to its original state. For example, if one test you write requires you to populate a table with a few rows. Well, after that test finishes, this trait will clear out those rows automatically.

Use it, like so:

<?php

use Laracasts\Integrated\Extensions\Laravel as IntegrationTest;
use Laracasts\Integrated\Services\Laravel\DatabaseTransactions;

class ExampleTest extends IntegrationTest {
  use DatabaseTransactions;
}

Done!

TestDummy

To help with RAD, this package includes the "laracasts/testdummy" package out of the box. For integration tests that hit a database, you'll likely want this anyways. Refer to the TestDummy documentation for a full overview, but, in short, it gives you a very simple way to build up and/or persist your entities (like your Eloquent models), for the purposes of testing.

Think of it as your way of saying, "Well, assuming that I have these records in my database table, when I yadayada".

use Laracasts\TestDummy\Factory as TestDummy;

// ...

/** @test */
function it_shows_posts()
{
  TestDummy::create('App\Post', ['title' => 'Example Post']);

  $this->visit('/posts')->andSee('Example Post');
}
Clone this wiki locally