Let’s say that we have a Service that reads and writes to Redis.
We have BaseRedisService for managing connection,
RedisWriterService to write to Redis and
RedisReaderService to read from Redis.
A test for the above mentioned case might look like this.
But now, we need to add PubSub to the service and verify that
the service sends proper messages to Redis.
For verifying from such a service, the service would need to listen to messages sent to Redis.
Problem is that Redis listens in a loop. We would need to explicitly release control from listening and
allow our tests to go ahead and verify some scenario.
Lets look at how these services would look.
and our Subscriber looks like this.
Notice that we don’t have control over returning value from the loop easily. Right now we just print on receiving a new message.
Now, lets start persisting our messages to some array in our Service.
Also we will start exposing this from a thread variable so that it could be accessed from outside of execution
of this listen loop.
We now have a way to access message state from the service to read any messages received by it.
Lets say we define a new SubscriberService from a Thread, we could read messages like this.
Armed with this, we can now define a set of Rails helpers to use in our Rails tests.
Notice the with_subscriber method. It executes some code passed to it, then passes method
execution to the subscriber process to read any messages sent and store onto messages store.
The count of the variable THREAD_PROCESS_TIMEOUT, can be experimented to set to a value
that suites the system that’s being verified.
In our tests, we can now verify PubSub as-
We took a look at how PubSub based services can be verified by using threads and exposing
messages from them, for verification. These can be tailored to support any similar PubSub
service like Redis, and can be used to easily verify values being published from our services
from Rails tests.
Share this article:
Subscribe to our monthly newsletter
Thank you! You have successfully subscribed to our newsletter.