samedi 10 janvier 2015

Beter way to test if method is called x times with MiniTest?

Today I've started with some basic implementation of minitest and finally figured a way out to test if a method on a class is called twice.


In RSpec I would do something like:



expect(@foo).to receive(:some_heavy_calculation).twice
@foo.bar


Now, I've came up with the following implementation for MiniTest, but I'm not sure if this is the way to implement this, because this. Here's what I've got



require 'minitest/autorun'

class Foo
def bar
@cached_value ||= some_heavy_calculation
end

def some_heavy_calculation
"result"
end
end

class FooTest < Minitest::Test
def setup
@foo = Foo.new
end

def cache_the_value_when_calling_bar_twice
mock = Minitest::Mock.new
mock.expect(:some_heavy_calculation, [])
@foo.stub :some_heavy_calculation, -> { mock.some_heavy_calculation } do
2.times { assert_equal_set @foo.bar, [] }
end
mock.verify
end
end


Do I really have to implement this with a mock, which will be the result of the stub of the subject on the method that has to be called x times?


Aucun commentaire:

Enregistrer un commentaire