How to test Redis Lock via Rspec?

258 views
Skip to first unread message

Saurav Kothari

unread,
Aug 9, 2018, 6:32:24 AM8/9/18
to Ruby on Rails: Talk

We have a Lockable concern that allows for locks via Redis


module Lockable
  extend ActiveSupport::Concern

  def redis_lock(key, options = {})
    Redis::Lock.new(
      key,
      expiration: options[:expiration] || 15,
      timeout: options[:timeout] || 0.1
    ).lock { yield if block_given? }
  end
end



We use this in a Controller method to ensure concurrent requests are handled correctly.


def create
  redis_lock(<generated_key>, timeout: 15) do
    # perform_operation
  end

  render json: <data>, status: :ok
end


When testing this action, I want to test that the correct generated_key is being sent to Redis to initiate a lock.


I set up an expect for the Redis::Lock but that returns false always presumably because the request to create is sent mid request and not at the end of it.

expect(Redis::Lock).to receive(:create).once



Since the lock is cleared at the end of the method call, I cannot check for the key in redis as a test.


This answer recommends setting up a fake class that matches the structure of Lockable to emulate the same behaviour but how do I write a test for it? The method we have does not return any value to verify.


<SO link to the same question>

Hassan Schroeder

unread,
Aug 9, 2018, 11:26:43 AM8/9/18
to rubyonrails-talk
On Thu, Aug 9, 2018 at 3:32 AM, Saurav Kothari <sauravk...@gmail.com> wrote:

> We have a Lockable concern that allows for locks via Redis

> When testing this action, I want to test that the correct generated_key is
> being sent to Redis to initiate a lock.

What is the definition of "correct" here? Wouldn't it be easier to just
test the "correctness" of the producer of that key?

--
Hassan Schroeder ------------------------ hassan.s...@gmail.com
twitter: @hassan
Consulting Availability : Silicon Valley or remote
Reply all
Reply to author
Forward
0 new messages