Sachin Singh
Sachin Singh

Reputation: 7225

how to mock instance method of another class in minitest

i am testing ruby application using minitest

and i have scenario like this:

class TestExample

   def test_method
      SomeOtherClass.new.print_message "Hello World!!!!!"
   end

end

here i want to mock print_message method of SomeOtherClass, and tried it like this

mock = MiniTest::Mock.new
test_example = TestExample.new
mock.expect(SomeOtherClass.new, nil, ["Hello World!!!!!"])
test_example.test_method
mock.verify

its does not work, it gives exception like: -

MockExpectationError: expected #("Hello World!!!!!") => [], got []

thanks for any suggestion and answer.

Upvotes: 2

Views: 2896

Answers (1)

Panic
Panic

Reputation: 2405

class TestMocking < MiniTest::Unit::TestCase
  def test_mocking
    some_other_class_mock = MiniTest::Mock.new
    some_other_class_mock.expect :print_message, nil, ["Hello World!!!!!"]

    SomeOtherClass.stub :new, some_other_class_mock do
      test_example = TestExample.new
      test_example.test_method
    end

    some_other_class_mock.verify
  end
end

Upvotes: 5

Related Questions