Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby MiniTest UnitTest Stubbing Class method just for one test

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.

like image 591
manoj Avatar asked Dec 02 '14 13:12

manoj


1 Answers

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
like image 72
Chris Kottom Avatar answered Oct 16 '22 06:10

Chris Kottom