新手使用Cucumber时出现$?.success? no method error错误

4

我正在进行“务实的Cucumber”第一个项目,但在我的步骤定义中遇到了未定义方法错误。错误来自于$?.success?。不用说,我很困惑。我是否缺少宝石或其他东西?

下面是步骤定义:

Given /^the input "(.*?)"$/ do |input|
  @input = input
end

When /^the calculator is run$/ do
  @output = 'ruby calc.rb #{@input}'
  raise('Command failed!') unless $?.success? #$?.success? is failing. look that up.
end

Then /^the output should be "(.*?)"$/ do |arg1|
  pending # express the regexp above with the code you wish you had
end

这里是错误信息。
Feature: Adding

  Scenario: Add two numbers       # features/adding.feature:3
Given the input "2+2"         # features/step_definitions/calculator_steps.rb:1
When the calculator is run    # features/step_definitions/calculator_steps.rb:5
  undefined method `success?' for nil:NilClass (NoMethodError)
  ./features/step_definitions/calculator_steps.rb:7:in `/^the calculator is run$/'
  features/adding.feature:5:in `When the calculator is run'
Then the output should be "4" # features/step_definitions/calculator_steps.rb:10

Failing Scenarios:
cucumber features/adding.feature:3 # Scenario: Add two numbers

1 scenario (1 failed)
3 steps (1 failed, 1 skipped, 1 passed)
0m0.012s

那么,问题出在哪里呢?我知道 .success? 是正确的,为什么 $? 没有被注册呢?谢谢!

2个回答

10
你需要使用反引号而不是引号来运行命令:
@output = 'ruby calc.rb #{@input}'

应该是:

@output = `ruby calc.rb #{@input}`

编辑:

刚刚测试了一下 - 在使用这种结构时要非常小心。 $? 的值不会在 Cucumber 场景之间清除,因此很容易针对先前场景中运行的命令结果做出断言。您可能希望研究 Aruba,它专门设计用于需要 Cucumber 执行或针对命令行程序进行断言的情况。


这个完美地运行了(我知道这是一些愚蠢的东西)。我一定会去看看阿鲁巴。非常感谢。 - CRBairdUSA
有没有类似于 Aruba 的 Rspec 工具? - Tasdik Rahman

1

代码ruby calc.rb #{@input}是一个Shell命令 - 在反引号中包含命令是告诉Ruby你想执行Shell命令的一种方式。这个链接将为您提供有关在Ruby中运行Shell命令的其他方法的一些信息。

这个讨论在Pragmatic Bookshelf论坛上专门回答了您的问题,并且还围绕这个主题进行了一些讨论,如果您想学习更多知识,这总是很好的。如果您有关于Cucumber书籍的特定问题,并且希望从权威人士那里获得答案,那么这个论坛可能是您最好的选择。


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