Quintus Chen
Quintus Chen

Reputation: 15

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'.

custom_mod.rb:

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

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.

Any ideas? Thanks so much!

Upvotes: 0

Views: 1235

Answers (2)

l-l
l-l

Reputation: 3854

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

Upvotes: 1

max pleaner
max pleaner

Reputation: 26768

Yes, it's a very simple fix, you just use def self.my_method()

This is very fundamental Ruby OOP stuff. With either modules or classes, you need to use "class methods" (that's what the self. does) to call methods in this way.

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). Module class methods cannot be used as mixins in the same way.

Upvotes: 0

Related Questions