Reputation: 11
I'm using Mocha for mock testing. Below is the relevant code:
# 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
The test failed, complaining that there was an "unexpected invocation: #.fetch_points_per_game(any_parameters)"
My understanding of my code is if @point_per_game is nil, fetch_points_per_game will be called, otherwise, the result is cached for future calls to points_per_game. So why is the test complaining that fetch_points_per_game was called twice?
Upvotes: 1
Views: 3726
Reputation: 696
In your expectation, you're not specifying a return value, so the stubbed call returns nil. This is why it's being called a second time. If you change the expectation to:
@durant.expects(:fetch_points_per_game).at_most_once.returns(1.23)
You should find that the tests now pass.
Upvotes: 3