Kenneth Stoddard
Kenneth Stoddard

Reputation: 1449

Use Laravel Eloquent from within Behat/Mink FeatureContext

This question assumes some knowledge of Laravel, Behat, and Mink.

With that in mind, I am having trouble making a simple call to the DB from within my Behat FeatureContext file which looks somewhat like this...

<?php

use App\Models\Db\User;
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use Behat\MinkExtension\Context\MinkContext;

/**
 * Defines application features from the specific context.
 */
class FeatureContext extends MinkContext implements Context {
    public function __construct() {}

    /**
     * @Given I am authenticated with :email and :password
     */
    public function iAmAuthenticatedWith($email, $password) {
        User::where('email', $email)->firstOrFail();

        $this->visitPath('/login');
        $this->fillField('email', $email);
        $this->fillField('password', $password);
        $this->pressButton('Login');
    }
}

When this scenario runs I get this error...

Fatal error: Call to a member function connection() on null (Behat\Testwork\Call\Exception\FatalThrowableError)

Which is caused by this line...

User::where('email', $email)->firstOrFail();

How do I use Laravel Eloquent (make DB calls) from within a Behat/Mink FeatureContext? Do I need to expose something within the constructor of my FeatureContext? Update/add a line within composer.json or behat.yml file?

If there is more than one way to solve this problem and it is worth mentioning, please do.

Additional Details

Behat Config

default:
  extensions:
    Behat\MinkExtension\ServiceContainer\MinkExtension:
      base_url: "" #omitted 
      default_session: selenium2
      selenium2:
        browser: chrome

Upvotes: 2

Views: 595

Answers (1)

filipe
filipe

Reputation: 2047

Laravel need to setup the eloquent and the connection for this to work.

The easy way is to extend laravel TestCase and in the __constructor() call parent::setUp();

It will setup your test environment, like it does when you run php test units in Laravel:

    /**
     * Setup the test environment.
     *
     * @return void
     */
    protected function setUp()
    {
        if (! $this->app) {
            $this->refreshApplication();
        }
        $this->setUpTraits();
        foreach ($this->afterApplicationCreatedCallbacks as $callback) {
            call_user_func($callback);
        }
        Facade::clearResolvedInstances();
        Model::setEventDispatcher($this->app['events']);
        $this->setUpHasRun = true;
    }

The refreshApplication() will call the createApplication() and it does bootstrap the Laravel and create the $this->app object.

    /**
     * Refresh the application instance.
     *
     * @return void
     */
    protected function refreshApplication()
    {
        $this->app = $this->createApplication();
    }

Upvotes: 3

Related Questions