Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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????

like image 318
Angela Tian Avatar asked Apr 21 '16 04:04

Angela Tian


People also ask

What is stubbing in RSpec?

In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet.

How do I mock a method in RSpec?

Mocking with RSpec is done with the rspec-mocks gem. If you have rspec as a dependency in your Gemfile , you already have rspec-mocks available.

What is the difference between stubs and mocks in Ruby testing?

Stub: A class or object that implements the methods of the class/object to be faked and returns always what you want. Mock: The same of stub, but it adds some logic that "verifies" when a method is called so you can be sure some implementation is calling that method.

What is allow in RSpec?

Use the allow method with the receive matcher on a test double or a real. object to tell the object to return a value (or values) in response to a given. message. Nothing happens if the message is never received.


1 Answers

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.

like image 60
Rendrum Avatar answered Oct 28 '22 14:10

Rendrum