How do I mock a Class with Ruby?

放肆的年华 提交于 2019-12-04 07:21:13

I think that's 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)

After running into the same problem and thinking about it for quite a while, I found that temporarily changing the class constant is probably the best way to do it (just as Elliot suggests in his answer).

However, I found a nicer way to do it: https://github.com/adammck/minitest-stub-const

Using this gem, you could write your test like this:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!