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????
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With