You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Ruby-Cucumber的Cucumber表达式实现多步骤复用同一定义

Ruby-Cucumber 复用步骤定义的Cucumber表达式写法

你的场景步骤如下:

Given something
When the sky is blue
And grass is green
Then I'm happy

要避免编写重复的步骤定义,使用Cucumber表达式可以通过枚举匹配的方式让两个When步骤共用同一个定义,语法如下:

When('(the sky is blue|grass is green)') do
  puts 'good'
end

说明:

  • 用括号()包裹所有需要匹配的步骤文本选项
  • 不同选项之间用竖线|分隔
  • Cucumber中And会继承前面的步骤关键字,因此And grass is green会被识别为When grass is green,和第一个步骤匹配同一个定义
  • 如果后续需要新增类似步骤,直接在括号内添加新选项即可

内容的提问来源于stack exchange,提问作者Andrew Walker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 22:13:13