1

我有一个 Ruby-Cucumber 框架。我需要使用该方法method_missing来避免编写一些重复的函数。我应该把我的放在哪里method_missing?在文件夹.rb下的任何文件中support?还是应该放在一些不同的特定文件中?

4

1 回答 1

1

在目录中的文件和模块中定义method_missing任何 Cucumber 辅助方法,然后将其传递给Cucumber.rbsupportWorld

module MethodMissing
  def method_missing(method)
    puts "You said #{method}"
  end
end
World MethodMissing

然后,您可以在步骤定义中调用缺失的方法。

像任何 Cucumber 辅助方法一样,method_missing应该只在 Cucumber 上定义World。如果您在支持文件的顶层定义它,它将在 Ruby 顶层对象上定义并且随处可用,这是不简约的并且可能会破坏其他代码。

我故意不遵守super,因为World不定义method_missing或定义respond_to_missing?,因为我没有任何计划调用method(:foo)World但是如果您更愿意在定义时始终执行这些操作,则可以执行这些操作method_missing

于 2016-08-31T13:24:30.023 回答