2014-10-29 27 views
1

我習慣於RSpec,在其中您可以用evalueted lazily的塊來存根方法實現。當用摩卡碎片時替換方法實現

現在我正在處理一個使用Test :: Unit和mocha作爲嘲諷庫的項目的請求。

我需要能夠做類似於rspec示例的東西,即用取決於對象狀態的動態方法替換方法實現,所以我不能使用由mocha #returns方法提供的靜態調用。

有什麼辦法可以用摩卡獲得相同的功能,我無法找到關於此的任何文檔?

我需要實現與此類似(2.14 RSpec的語法)的東西

class SomeController < ApplicationController 
    before_filter :authenticate 

    def authenticate 
    # original method I need to replace 
    end 

    def some_other_method 
    :bar 
    end 

end 

describe SomeController do 

    before do 
    controller.stub :authenticate do 
     redirect_to root_path if some_other_method == :foo 
    end 
    end 

    it 'should test something' do 
    controller.stub(some_other_method: :foo) 
    get :index 
    response.should redirect_to root_path 
    end 

    it 'should test something else' do 
    get :index 
    response.should be_successful 
    end 

end 

回答

1

你就不能在controller實例中使用def

def controller.some_other_method 
    :foo 
end 
+0

我在試驗過程中自己找到了同樣的答案。通常最簡單的事情是最有效的。整個例子比我發佈的更復雜,但我可以重構測試以使用這種方法。 – Fabio 2014-10-29 14:51:28

+1

如何在此之後清理並恢復原始定義? – 2015-10-11 15:08:23

+0

您可以別名舊方法,然後以相反方式恢復它,也可以使用優化僅在當前規範文件中進行更改。但是,如果可以的話,我推薦使用不同的庫,一個支持動態存根。例如http://rr.github.io/rr/,雖然我沒有用過它自己。 – 2015-10-11 16:30:41