I want to stub a class method for just one test and for the rest of the tests, i want the actual method to be called. I have always been using rspec and mocha, so the below behavior looks bizarre.
The class that i want to stub in one of my tests.
class MyClass
def self.foo(arg)
return "foo#{arg}"
end
end
The test where i try to stub MyClass.foo
class XYZTest < Minitest::Test
def test_1
MyClass.expects(:foo).returns('abcd')
assert_equal MyClass.foo('123'), 'abcd'
end
def test_2
assert_equal MyClass.foo('123'), 'foo123'
end
end
The first test passes, but the second test fails stating Mocha::ExpectationError: unexpected invocation: MyClass.foo('123')
In the test_2, i want the actual class method to be called instead of the stub that i did in test_1.
PS: Above is a striped down example. I do not want to reset everytime, I stub the class method.
Minitest stubs methods within a block, so what you're trying to do is simple.
class XYZTest < Minitest::Test
# stubbed here
def test_1
MyClass.stub(:foo, 'abcd') do
assert_equal MyClass.foo('123'), 'abcd'
end
end
# not stubbed here
def test_2
assert_equal MyClass.foo('123'), 'foo123'
end
end
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