behave / behave-django

Behave BDD integration for Django
https://behave-django.readthedocs.io/
MIT License
205 stars 46 forks source link

multiple features and before_all initial setup #118

Closed DragosChirila closed 3 years ago

DragosChirila commented 3 years ago

Hi,

In a Django project I have inside an app a /features folder with 3 features let's call them: 1.feature, 2.feature and 3.feature.

In my environment.py file I have implemented the before_all hook to populate the database with some records needed in all 3 features, something like:

def before_all(context):
    context.user = User.objects.create(....)

Now, if I execute features one after another like:

python manage.py behave myapp/tests/features/1.feature
python manage.py behave myapp/tests/features/2.feature
python manage.py behave myapp/tests/features/3.feature

everything works fine. Also this works if I use --keepdb argument.

But, If I try this command:

python manage.py behave myapp/tests/features/

then after the 1st feature the user object created in before_all is gone from the database. The strange thing is that context.user returns a valid User object and I have a PK for it, I have printed some debug info in the console:

print('context.user = ', context.user, context.user.pk)
->
context.user = test@localhost.com 24

But if I try to create a relation with that user then I get app.models.DoesNotExist: User matching query does not exist.

I was wondering if I am missing something here? Also, is there a database flush between features?

Any ideas are highly appreciated.

Thank you very much, Dragos

bittner commented 3 years ago

You're looking for the before_scenario hook. See the related note in the Fixture Loading chapter.

The documentation says on Test Isolation:

Each scenario is run inside a database transaction, just like your regular TestCases.

That's why you should load your fixtures before each scenario. We ensure proper isolation this way.

Is this counter-intuitive or otherwise problematic?

DragosChirila commented 3 years ago

Hi @bittner ,

Thank you very much for your answer. It makes sense, somehow I overlooked before_scenario. Since all my scenarios have a common setup, I thought that all the initial objects should be created in before_all.

Cheers, Dragos