2013-05-01 70 views
0

我正在使用摩卡進行模擬測試。下面是相關代碼:摩卡預計最多一次,被調用兩次,但方法顯然只能調用一次

# test_player.rb 
should "not download the ppg more than once for a given year" do 
    @durant.expects(:fetch_points_per_game).at_most_once 
    ppg = @durant.points_per_game 
    ppg2= @durant.points_per_game 
    assert_equal ppg, ppg2, "A player should have a points per game" 
end 

# player.rb 
class Player 
    # ... 

    def points_per_game(year=Date.today.year) 
    @points_per_game ||= fetch_points_per_game(year) 
    end 
    alias_method :ppg, :points_per_game 

    private 

    def fetch_points_per_game(year=Date.today.year) 
    31.2 
    end 
end 

試驗失敗了,抱怨說,有一個「意想不到的調用:#.fetch_points_per_game(any_parameters)」

我的我的代碼的理解是,如果@point_per_game爲零,fetch_points_per_game將被調用,否則,結果被緩存以便將來調用points_per_game。那麼爲什麼測試抱怨fetch_points_per_game被調用了兩次?

回答

1

根據您的預期,您沒有指定返回值,因此存根調用返回nil。這就是爲什麼它被稱爲第二次。如果您將期望更改爲:

@durant.expects(:fetch_points_per_game).at_most_once.returns(1.23) 

您應該發現測試現在已通過。

相關問題