1

I was struggling with testing module's def self.method. I found a great thread here with a very helpful answer. My code is:

module MyModule
  def self.method
    groups = Posts.group :name
  end
end

describe Class.new { include MyModule } do
  its (:method) { should be_a(ActiveRecord::Relation) }
end

The problem is, that the question is about including a module, and not extending it. As the author of the answer mentioned, he tested it with RSpec 2. I tested it with RSpec 3.0.0 and the only thing that worked was when the method was an instance's method. Otherwise I'm getting the following error:

undefined method `method' for #<#<Class:0x0000000..>:0x00000006..>

How can I test the MyModule.method?

Community
  • 1
  • 1
valk
  • 9,363
  • 12
  • 59
  • 79

1 Answers1

1

It might be getting an instance and class level method confused. Try this to be sure it's really testing on the Class-level method

class MyClass
  include MyModule
end
it "should have an active relation on method" do
  expect(MyClass.method).to be_a(ActiveRecord::Relation)
end
Taryn East
  • 27,486
  • 9
  • 86
  • 108
  • With that precise setup I'm getting this error `undefined method 'method' for DummyClass:Class` :-/ – valk Aug 14 '14 at 06:40
  • right, so your include isn't doing what you think it's doing... which means that perhaps `include` is not what you want. – Taryn East Aug 14 '14 at 06:43
  • You're right. I'm upvoting this, thanks. I think my question is confusing. But how would you test a module's self method anyway? – valk Aug 14 '14 at 07:00
  • 2
    The problem with modules is that they don't evaluate class methods the same way... I would normally use extend (not include) for the class methods in order for them to get into a class. or if I'm using Active Model I can use `included` ... – Taryn East Aug 14 '14 at 07:27