Search code examples
ruby-on-railsrspec

Rspec how to stub module instance method?


B.rb looks like:

module A
   module B

     def enabled? xxx
        xxx == 'a'
     end

     def disabled? xxx
       xxx != 'a'
     end
   end
end

Another C.rb like:

module YYY
  class C
  include A::B

  def a_method 
     if(enabled? xxx) 
       return 'a'
     return 'b'
  end
end

Now I want to write unit tests to test a_method function,

 describe :a_method do
    it 'returns a' do
       ###how to sub enabled? method to make it return true....
    end
 end 

enabled? is the instance method in the model, I tried

A::B.stub.any_instance(:enabled).and_return true

it doesn't work.

anyone can help me????


Solution

  • You are stubbing wrongly. Your A::B is a module, so you don´t have instances, instances are of classes. You forget the question mark also.

    Try this to stub your module static method:

    A::B.stub(:enabled?).and_return true
    

    And in the second example (if you need) try this:

    YYY::C.any_instance.stub(:a_method).and_return something
    

    But I think you are trying to stub the enabled? method in the class YYY::C, so you need to use this:

    YYY::C.any_instance.stub(:enabled?).and_return true
    

    Then when calling :a_method, enabled? will return true.