重新定义单元测试的方法

时间:2012-12-04 17:29:00

标签: ruby unit-testing

我不是用ruby语法编写的字符串,但是如果我在学习它时理解了一些东西,你可以做任何事情,没有限制,让我说我有一个类方法,我想在单元测试中重新定义它以隔离我正在测试的东西,我该怎么做?假设类名是foo,实例方法是bar。

1 个答案:

答案 0 :(得分:1)

Test::Redef是一个专门用来做这件事的宝石。

test "some method on Foo should be called because under normal circumstances it something useful like send network traffic" do
  Test::Redef.rd(
    'Foo#bar'  => proc {|args| puts 'new behavior goes here!'},
    'Foo#baz'  => :empty,   # same as => proc { }
    'Foo#quux' => :wiretap, # no behavior change but you get invocation tracking
    'Foo.blat' => :empty,   # class method
  ) do |rd|

    # code under test


    assert_equal [['invocation 1 arg 1', 'invocation 1 arg 2'], 
                  ['invocation 2 arg 1'],
                 ], rd[:bar].args, 'Foo#bar was called with the right arguments'
  end

  # now all methods are back to normal
end