简体   繁体   English

Ruby Cucumber-在步骤定义中调用模块的方法

[英]Ruby Cucumber - call a module's method in step definition

In a step definition, when I tried to call a method defined in a module in another file, I got 'NoMethodError'. 在步骤定义中,当我尝试调用另一个文件的模块中定义的方法时,出现“ NoMethodError”。

custom_mod.rb : custom_mod.rb

module MyMod
    def my_method()
        puts "Called my_method"
    end
end

sd_component.rb: sd_component.rb:

require 'custom_mod'
When (/^I did something/) do
    MyMod.my_method()
end

And when I run it I get this error: 当我运行它时,出现此错误:

NoMethodError: undefined method `my_method' for MyMod:Module. NoMethodError:MyMod:Module的未定义方法“ my_method”。

Any ideas? 有任何想法吗? Thanks so much! 非常感谢!

One way to fix this is to include your module like this: 解决此问题的一种方法是包括如下所示的模块:

require 'custom_mod'
include MyMod
When (/^I did something/) do
    my_method()
end

Yes, it's a very simple fix, you just use def self.my_method() 是的,这是一个非常简单的修复,您只需使用def self.my_method()

This is very fundamental Ruby OOP stuff. 这是非常基本的Ruby OOP东西。 With either modules or classes, you need to use "class methods" (that's what the self. does) to call methods in this way. 无论是模块还是类,您都需要使用“类方法”(这就是self.所做的)来以这种方式调用方法。

Compare this to instance methods: 将此与实例方法进行比较:

module Foo2
  def bar2
    'bar2'
  end
end

class Foo
  include Foo2
  def bar
    'bar'
  end
end

Foo.new.bar # => 'bar'
Foo.new.bar2 # => 'bar2'

Note that instance methods work differently on modules than classes. 请注意,实例方法在模块上的作用与在类上的作用不同。 Module instance methods can be mixed in (load them as instance methods with include or as class methods with extend ). 可以混入模块实例方法(将它们作为include实例方法或作为具有extend类方法加载)。 Module class methods cannot be used as mixins in the same way. 模块类方法不能以相同的方式用作混合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM