我在 ruby 语法中不是那么严格,但是如果我在学习它时理解了一些东西,你可以做任何事情,没有任何限制,假设我有一个类方法,我想在单元测试中重新定义它以隔离我的东西正在测试,我该怎么做?假设类名是 foo,实例方法是 bar。
问问题
351 次
1 回答
1
Test::Redef is a gem designed to do exactly this.
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
于 2013-10-15T16:12:46.630 回答