Home > Software engineering >  Assert that Ruby module extends another module
Assert that Ruby module extends another module

Time:05-13

I have two modules A & B, I am extending A into B in order to use the methods of A in B as class methods:

module A
   def foo
   end 
end 

module B
   extend A
end 

B.Foo

I'd like to write a test to assert that module B Extends A. Currently Ruby does not implement an extends? method but I think that would be a great idea. Is there anyway to assert that a module extends another module? I could use the responds_to? method but I'd have to loop over all of the methods in the extending module and that in my opinion is not a great design. Thanks again, peace.

CodePudding user response:

I agree with @spickermann's comment that it doesn't seem like a useful test, that said:

included_singleton_modules = B.singleton_class.included_modules #[A, Kernel]
assert(included_singleton_moduls.include? A)

Gives you what you want.

CodePudding user response:

class C
  include M
end

essentially just "inserts" M into the ancestry chain as the superclass of C. Or, more precisely, it creates an include class from M, makes that include class the superclass of C and the old superclass of C the superclass of the include class.

Furthermore,

class C
  extend M
end

is essentially just the same as

class << C
  include M
end

i.e. it inserts M into the the ancestry chain of the singleton class of C.

Since C is an instance of its singleton class and M is the superclass of the singleton class, C is an instance of M.

What this means is that all you need to do is

B.is_a?(A)
#=> true

However, as mentioned in other answers and comments, you don't really care that B is an instance of A. What you do care about is that when you call B.foo, you get the behavior that you expect. So, assert that.

  • Related