From 36eb08a8c7667b8bf5447cbfccebff95b33920af Mon Sep 17 00:00:00 2001 From: vu-hoang-kaligo Date: Mon, 13 Jan 2025 08:15:34 +0700 Subject: [PATCH] Support testing by mocking MockRedis#evalsha --- Gemfile.lock | 2 +- README.md | 11 +++++++++++ lib/idempotency/testing/helpers.rb | 29 +++++++++++++++++++++++++++++ lib/idempotency/version.rb | 2 +- 4 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 lib/idempotency/testing/helpers.rb diff --git a/Gemfile.lock b/Gemfile.lock index d15265e..7191e9e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - idempotency (0.1.2) + idempotency (0.1.3) base64 dry-configurable msgpack diff --git a/README.md b/README.md index a787551..a29d961 100644 --- a/README.md +++ b/README.md @@ -89,3 +89,14 @@ end # Render your response ``` + +### Testing + +For those using `mock_redis` gem, some methods that `idempotency` gem uses are not implemented (e.g. eval, evalsha), and this could cause test cases to fail. To get around this, the gem has a monkeypatch over `mock_redis` gem to override the missing methods. To use it, simply add following lines to your `spec_helper.rb`: + +```ruby +RSpec.configure do |config| + config.include Idempotency::Testing::Helpers +end +``` + diff --git a/lib/idempotency/testing/helpers.rb b/lib/idempotency/testing/helpers.rb new file mode 100644 index 0000000..655a99b --- /dev/null +++ b/lib/idempotency/testing/helpers.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +require 'idempotency/cache' + +class Idempotency + module Testing + module Helpers + def self.included(_base) + return unless defined?(MockRedis) + + MockRedis.class_eval do + def evalsha(sha, keys:, argv:) + return unless sha == Idempotency::Cache::COMPARE_AND_DEL_SCRIPT_SHA + + value = argv[0] + cached_value = get(keys[0]) + + if value == cached_value + del(keys[0]) + value + else + cached_value + end + end + end + end + end + end +end diff --git a/lib/idempotency/version.rb b/lib/idempotency/version.rb index 7220cf3..d8744e3 100644 --- a/lib/idempotency/version.rb +++ b/lib/idempotency/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class Idempotency - VERSION = '0.1.2' + VERSION = '0.1.3' end