vendredi 15 juin 2018

Test cached (multiprocessed) and memoized method

Short question, I'd like to test this method foo:

class MyClass
    def foo
        # The `@cache_key` is defined by instance but can be the same for
        # different instances (obviously I guess)
        @foo ||= cache.fetch(@cache_key) do
            # call a private method, tested aside
            generate_foo_value || return
            # The `|| return` trick is one I use to skip the yield result
            # in case of falsey value. May not be related to the question,
            # but I left it there because I'm not so sure.
        end
   end
end

The issue here is that I have two kinds of caching.

On one hand, I have @foo ||= that assure memoization and that I can test pretty easily. For instance by calling twice my method and watch if the result is different.

On the other hand, I have the cache.fetch method which may be shared between different instances. The trouble for me is here: I don't know the best way to unit test it. Should I mock my cache? Should I watch cache result? Or should I run plural instances with the same cache key?

And for this last question, I don't know how to run plural instances easily using rspec.

Aucun commentaire:

Enregistrer un commentaire