如何使用Ruby模拟类? [英] How do I mock a Class with Ruby?

查看:189
本文介绍了如何使用Ruby模拟类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用minitest /模拟,并想模拟一个类。我不是试图测试模型类本身,而是试图测试一个服务(SomeService)与模型(SomeModel)交互。

I'm using minitest/mock and would like to mock a class. I'm not trying to test the model class itself, but rather trying to test that a service (SomeService) interacts with the model (SomeModel).

我想出了这个(Hack :: ClassDelegate),但我不相信这是一个好主意:

I came up with this (Hack::ClassDelegate), but I'm not convinced it's 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 pretty sure that mocking a class is not a great idea anyway, but I have a legacy system that I need to write some tests for and I don't want to change the system until I've wrapped some tests around it.

推荐答案

我认为这是有点复杂。这样做:

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)

这篇关于如何使用Ruby模拟类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆