pythonbddpython-behave

Can I put step definitions in a folder which is not "steps" with behave?


I am trying to work with Behave on Python. I was wondering if there would be a way to put my .py files somewhere else instead of being forced to put them all inside the "steps" folder. My current structure would look like this

tests/
    features/
    steps/ #all code inside here, for now

What I would like to accomplish is something like

tests/
    features/ #with all the .feature files
    login/ #with all the .py files for logging in inside a service
    models/ #with all the .py files that represents a given object
    and so on

The only BDD framework that I used before Behave was Cucumber with Java, which allowed to insert the step definitions wherever I wanted to (and the rest was handled by Cucumber itself). I am asking this because I would like to have a lot of classes in my project in order to organize my code in a better way.


Solution

  • First, from the behave Documentation (Release 1.2.7.dev0):

    behave works with three types of files:

    1. feature files written by your Business Analyst / Sponsor / whoever with your behaviour scenarios in it, and
    2. a “steps” directory with Python step implementations for the scenarios.
    3. optionally some environmental controls (code to run before and after steps, scenarios, features or the whole shooting match).

    So a steps/ directory is required.

    To accomplish a workaround similar to what you have in mind, I tried creating a subdirectory in the /steps directory: /steps/deeper/ and inserted my Python file there: /steps/deeper/testing.py. After running behave, I received the "NotImplementedError", meaning the step definitions in /deeper/testing.py were not found.

    It appears that behave doesn't search recursively through subdirectories of the steps/ directory for any additional Python files.

    As for what you're trying to do, I think it's decent organizational idea, but since it's not doable, you could do this: instead of having directories for the Python files in your tests/ directory, why not have a good naming convention for your Python file and separate the associated functions into their own Python files? That is:

    tests/
        features/
        steps/
            login_prompt.py # contains all the functions for logging in inside a service
            login_ssh.py # contains all the functions for SSH login
            models_default.py # contains all the functions for the default object
            models_custom.py # contains all the functions for a custom object
            and so on...
    

    Of course, at this point, it really doesn't matter if you separate them into different Python files, since behave searches through all the Python files in steps/ when called, but for organization's sake, it accomplishes the same effect.