Third-party services save time and effort but it might be challenging to test their performance.
I’m going to use Pusher as an example. That’s a service that sends push notifications.
Let’s say it is configured this way, included into a global variable.
And has a wrapper framing it:
Wrapper is helpful in case you need to change this third-party service and start sending push notifications with a different tool. Usually there is some sort of a channel and in this case we also send some event and its parameters. In other words, this is push notifier rule.
One of the ways to test the access to the service looks like this:
The main thing about this method is that the :process! parameter is set beforehand. The expect spec allows testing of that parameter. With this method you can add any type of expectations. Another way to do the same is to forcefully pass PushNotifier to some service – described_class.
And check if the method was requested by some parameters.
Looks a bit nicer, but the main difference from the previous method is in the timing. This is more logical way – first comes preparation, then requests, and then tests are run.
One more example, from a completely different project. Here I am building in a testing code into the production code.
SlackNotifier sends messages to slack by means of webhook to some URL as a post. In the SlackNotifier itself we create a setting (for example, fake) which either sends a real request to development or just exhibits itself in the tests without sending anything. This is a simple version of the method when they create a separate adaptor for HTTP net send and another adaptor for blocking.
One more thing here is that log creates records of sent messages for testing instead of sending them by HTTP.
Testing would look something like this:
Reminds of sidekiq and ActionMailer. I really don’t like littering the working class so I came up with a solution for Pusher, where there is no need to inherit. I can use WebMock to add method directly into Pusher. We are still littering sort of, but in test mode only.
The WebMock event after the request saves the variable of everything that was sent.
One of the benefits of this method which is my favourite is that a message I am trying to send into Pusher makes the whole circle, when being sent to the server, it gets caught by WebMock. This method creates minimum obstacles while tracking the data as it comes.
Testing looks like this:
Once you figure out the right approach and develop your testing strategy, it becomes easier to benefit from third-party services without any of the headache that comes with experiments.