Behat 3 and Laravel, testing environment not being

2020-07-23 08:39发布

问题:

I am having a confusing problem using Behat 3 and Laravel to test an API.

It seems that its not using the 'testing' environment database (in my case an sqlite memory database) ... but only some of the time.

I've put a log message in the testing/database.php file to see when its loaded.. and I do see the log message when running Behat.

But running the Behat features is adding rows to my development database - and some of my tests are failing for the same reason.

My phpunit tests run fine and do not alter the dev database.

Is there something that should be in behat.yml that I've missed?

EDIT: I see the problem - I am using Guzzle to test the API, and whereas Behat's setup functions are working on the testing env, once Guzzle is in play the app has no idea its in testing env. So I either have to find a way to tell the app its in testing env or tell behat to use the development env.

回答1:

With PHPUnit you can configure the environment in a bootstrap and that configuration will be used throughout the entire testing. With Behat you have a different situation, unlike PHPUnit, it makes requests to a server and doesn't talk to your Php code directly. Though to us, developers, it seems like we are testing the code that sits in the next folder to our features, in reality it is accessed via our local server, which points to that code. In other words you are dealing with a remote code that has zero exposure to your tests and ignores (as expected) the configuration (which you are setting on your local code anyway).

So, to pass any configuration to your code you need to think about your server as the entry point. There are two basic approaches – use two local domains for your app (app.dev and app.tst), or make your app.tst accept some parameter / cookie that will tell it that it's under the test. The first would be the best option as you are not adding any logic to your app and can setup environment variables via server config or make the domain point to a different bootstrap, etc.



回答2:

In your FeatureContext.php add this method:

/**
 * @BeforeSuite
 */
 public static function bootstrapLaravel()
 {
    $unitTesting = true;
    $testEnvironment = 'testing';


    require __DIR__ . '/../../../bootstrap/start.php'; // adjust this to right path. This will work if FeatureContext.php is in app/tests/acceptance
 }

This will use the testing database and include Laravel aswell (so you can use your models as well).