使用Python Behave编写Cucumber测试时步骤未定义问题求助
Hey there! Let's figure out why your behave steps are showing up as undefined. The main issue here is almost always that Behave can't locate your step definition file, or there's a tiny mismatch in how your steps are formatted. Let's break this down step by step.
1. Fix your project structure (most common culprit)
Behave follows a specific default directory structure to scan for step definitions. Right now, your test.py is in the same folder as test.feature, but Behave doesn't automatically pick up random .py files in that location. Here's the standard, trouble-free structure you should use:
your_project/ features/ test.feature steps/ test_steps.py # Move your step definitions into this file/folder
- Create a
stepssubfolder inside yourfeaturesdirectory (if you don’t have one already) - Rename your
test.pyto something liketest_steps.py(the name doesn’t strictly matter as long as it’s in thestepsfolder, but using a_stepssuffix makes it easier to identify) - Move this file into the
stepssubfolder
If you don’t want to rearrange your files, you can explicitly tell Behave where to find your step definitions with a command-line flag:
behave --steps-directory . test.feature
The . here tells Behave to look for step files in the current working directory.
2. Match your step text exactly (including quotes)
While this isn’t causing the "undefined" error right now, it will break your tests once Behave finds the steps. In your .feature file, values like DVD are wrapped in double quotes, but your step definitions don’t include those quotes in the decorator string.
Update your step definitions to mirror the feature file’s syntax exactly:
from behave import * @given('I have a new "{item}" in my cart') def step_impl(context, item): print("The item is: {}".format(item)) @when('I click on "{link}"') def step_impl(context, link): print("I am clicking the link: {}".format(link)) @then('I should see "{txt}"') def step_impl(context, txt): if txt not in ['success', 'error']: raise Exception("Unexpected text passed in.") print("Checking if I see the '{}' text".format(txt)) print("PASS. I see the '{}' text".format(txt))
This way, Behave will correctly extract the values inside the quotes (like DVD instead of "DVD") as parameters.
3. Double-check your imports
Quick sanity check: Make sure you’re importing the behave decorators correctly. Your current from behave import * is fine, but just confirm there are no typos (like misspelling behave or the decorator names).
Once you fix the directory structure (or use the --steps-directory flag) and adjust the step text to include the quotes, your tests should run without the undefined steps error.
内容的提问来源于stack exchange,提问作者meowcat

