如何在Cucumber步骤间传值?Context对象无survey_code属性报错
解决Cucumber中从@then步骤向@given步骤传递值的问题
错误原因
Cucumber的步骤执行顺序是Given(前置条件)→When(操作)→Then(断言),你的@given步骤会在@then步骤之前执行。当执行step_given_user_has_generated_survey_code时,context.survey_code还没被赋值,所以抛出AttributeError。
解决方案
方案1:调整步骤逻辑(符合BDD规范)
按照BDD的设计思路,Given步骤应该负责准备前置条件。把生成并获取survey_code的逻辑移到@given步骤中,后续步骤直接复用这个值:
@given('the user has a generated survey code') def step_given_user_has_generated_survey_code(context): # 执行生成survey_code的操作(比如点击生成按钮) context.driver.find_element(By.CSS_SELECTOR, "button#generate_survey_btn").click() # 获取并存储survey_code到context context.survey_code = context.driver.find_element(By.CSS_SELECTOR, "input#survey_code").get_attribute('value') print(444444444444444, context.survey_code) assert context.survey_code is not None @then('the user should see the generated survey code') def step_then_user_sees_generated_survey_code(context): # 从页面获取显示的code并和context中的值校验 displayed_code = context.driver.find_element(By.CSS_SELECTOR, "input#survey_code").get_attribute('value') print(22222222, displayed_code) assert displayed_code == context.survey_code
方案2:跨场景传递值(非推荐,仅用于特殊场景)
如果需要将上一个场景@then中获取的值传递到下一个场景的@given,可以用持久化存储(比如文件、环境变量):
import os @then('the user should see the generated survey code') def step_then_user_sees_generated_survey_code(context): context.survey_code = context.driver.find_element(By.CSS_SELECTOR, "input#survey_code").get_attribute('value') print(22222222, context.survey_code) assert context.survey_code is not None # 将值写入文件 with open('survey_code_temp.txt', 'w') as f: f.write(context.survey_code) @given('the user has a generated survey code') def step_given_user_has_generated_survey_code(context): # 从文件读取值 with open('survey_code_temp.txt', 'r') as f: context.survey_code = f.read().strip() print(444444444444444, context.survey_code) assert context.survey_code is not None # 可选:测试完成后清理临时文件 # os.remove('survey_code_temp.txt')
注意事项
- 优先使用方案1,BDD提倡每个场景独立且前置条件明确,跨场景依赖会让测试变得脆弱。
- 若用方案2,需确保临时文件在测试前不存在,或在测试结束后清理,避免干扰后续用例。
内容的提问来源于stack exchange,提问作者William
相关产品推荐
相关产品推荐

