Ruby + Cucumber:如何在代码中执行cucumber?

11

我希望能够在Ruby代码中执行Cucumber功能。

通常使用与gem安装的cucumber二进制文件,在命令行上指定一个或多个功能来执行。

然而,我想定义一些逻辑来创建动态的功能执行流。换句话说,程序可以确定应该执行哪些功能。

是否可能从Ruby代码中实例化Cucumber并指定功能文件,而不是在命令行上执行?

2个回答

12

我从邮件列表和一些API阅读中发现了这个。

features="path/to/first.feature path/to/second.feature"
runtime = Cucumber::Runtime.new 
runtime.load_programming_language('rb') 
Cucumber::Cli::Main.new([features]).execute!(runtime)

如果你希望执行宝石中 features/ 目录下所有的功能,请将一个空数组传递给 Main.new


有没有办法我可以传递某些参数?我的配置需要一些命令行参数来开始执行测试? - Sunilkumar V
1
你可以从源代码中看到,我传递的[features]是作为一个args参数传递的。这个参数会被cucumber/cli/configuration解析,使用cucumber/cli/options类。所以在我的例子中,你可能只需要将参数附加到features字符串的末尾。请确认是否有效。 - KomodoDave
我尝试了你告诉我的方法。在功能名称的末尾,我只是添加了我想要使用-P选项的cucumber配置文件。但是我收到了一个错误:“无效参数'xyz.feature --color -r features -p test_profile'”。所以它被传递给了方法,但是抛出了异常。 - Sunilkumar V
以下是堆栈跟踪:<code> 在 initialize' C:/Ruby200/lib/ruby/gems/2.0.0/gems/cucumber-1.3.16/lib/cucumber/feature_file.rb:58:in open' C:/Ruby200/lib/ruby/gems/2.0.0/gems/cucumber-1.3.16/lib/cucumber/feature_file.rb:58:in source' C:/Ruby200/lib/ruby/gems/2.0.0/gems/cucumber-1.3.16/lib/cucumber/feature_file.rb:37:in parse' C:/Ruby200/lib/ruby/gems/2.0.0/gems/cucumber-</code> - Sunilkumar V
尝试将每个参数都放入args数组中,像这样:[features,'--color','-r features','-p test_profile']。或者是[features,'--color','-r','features','-p','test_profile']。如果这两种方法都不行,那我就不知道解决方法了。 - KomodoDave
显示剩余4条评论

3

将指定了功能和选项的示例命令转换为:

cucumber features/first.feature features/second.feature -d -f Cucumber::Formatter::Custom

将其转换为Ruby代码,归结为向Cucumber传递一个args数组:
require 'cucumber'

# Method 1 - hardcoded features
args = %w(features/first.feature features/second.feature -d -f Cucumber::Formatter::Custom)

# Method 2 - dynamic features
features = 'features/first.feature features/second.feature'
args = features.split.concat %w(-d -f Cucumber::Formatter::Custom)

# Run cucumber
begin
  Cucumber::Cli::Main.new(args).execute!
rescue SystemExit
  puts "Cucumber calls @kernel.exit(), killing your script unless you rescue"
end

本文使用Ruby 2.0.0p598和Cucumber 1.3.17进行了测试。


你知道如何在AfterConfiguration钩子中运行一个功能吗?我已经初始化了Cucumber并想通过Ruby方法运行某些功能。 - Richlewis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接