How do I mock a class with Ruby?

I am using minitest / mock and would like to make fun of the class. I am not trying to test the model class itself, but trying to verify that the service (SomeService) interacts with the model (SomeModel).

I came up with this (Hack :: ClassDelegate), but I'm not sure if this is a good idea:

require 'minitest/autorun' require 'minitest/mock' module Hack class ClassDelegate def self.set_delegate(delegate); @@delegate = delegate; end def self.method_missing(sym, *args, &block) @@delegate.method_missing(sym, *args, &block) end end end class TestClassDelegation < MiniTest::Unit::TestCase class SomeModel < Hack::ClassDelegate ; end class SomeService def delete(id) SomeModel.delete(id) end end def test_delegation id = '123456789' mock = MiniTest::Mock.new mock.expect(:delete, nil, [id]) SomeModel.set_delegate(mock) service = SomeService.new service.delete(id) assert mock.verify end end 

I’m sure that mocking a class is not a great idea anyway, but I have a legacy system in which I need to write some tests, and I don’t want to change the system until I finish some tests around it.

+4
source share
2 answers

I think this is a little complicated. What about this:

 mock = MiniTest::Mock.new SomeService.send(:const_set, :SomeModel, mock) mock.expect(:delete, nil, [1]) service = SomeService.new service.delete(1) mock.verify SomeService.send(:remove_const, :SomeModel) 
+5
source

After I ran into the same problem and thought about it for a while, I found that temporarily changing the class constant is probably the best way to do this (as Elliot prompts in his answer).

However, I found a more convenient way to do this: https://github.com/adammck/minitest-stub-const

Using this gem, you can write your test as follows:

 def test_delegation id = '123456789' mock = MiniTest::Mock.new mock.expect(:delete, nil, [id]) SomeService.stub_const 'SomeModel', mock do service = SomeService.new service.delete(id) end assert mock.verify end 
+2
source

Source: https://habr.com/ru/post/1400019/


All Articles