我应该在 Cucumber Ruby 框架中的什么地方定义 method_missing?

Where should I define method_missing in a Cucumber Ruby framework?

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

定义 method_missing 就像您定义任何 Cucumber 辅助方法一样,在 support 目录中的 .rb 文件中以及随后传递给 the Cucumber World 的模块中:

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?,因为我没有计划在 World 上调用 method(:foo),但如果您希望在定义 method_missing.

时始终执行这些操作,则可以执行这些操作