2014-12-02 60 views
2

我想为一个测试和其他测试存根类方法,我希望实际的方法被调用。我一直使用RSpec和摩卡,所以下面的行为看起来很奇怪。Ruby MiniTest UnitTest Stubbing类方法仅用于一个测试

我想在我的一个测试中存根的类。

class MyClass 
    def self.foo(arg) 
    return "foo#{arg}" 
    end 
end 

测试,其中i尝试末梢MyClass.foo

class XYZTest < Minitest::Test 
    def test_1 
    MyClass.expects(:foo).returns('abcd') 
    assert_equal MyClass.foo('123'), 'abcd' 
    end 

    def test_2 
    assert_equal MyClass.foo('123'), 'foo123' 
    end 
end 

第一测试通过,但第二个测试失败,说明摩卡:: ExpectationError:意想不到调用:MyClass.foo( '123' )

在test_2中,我想调用实际的类方法,而不是我在test_1中做的存根。

PS:上面是一个条纹的例子。我不想每次都重置,我将类方法存根。

回答

2

Minitest存根方块内的方法,所以你想要做的很简单。

class XYZTest < Minitest::Test 
    # stubbed here 
    def test_1 
    MyClass.stub(:foo, 'abcd') do 
     assert_equal MyClass.foo('123'), 'abcd' 
    end 
    end 

    # not stubbed here 
    def test_2 
    assert_equal MyClass.foo('123'), 'foo123' 
    end 
end