Mocking API Data
I have been working on a ruby slack bot with Fabien (another apprentice) that assists users at my company when ordering Lunch. This bot will message people who haven’t ordered asking them to order, but what happens if that person is out? Our bot shouldn’t waste its resources messaging someone who isn't even there!
So we got thinking, how could we mark someone as out automatically? Our company uses BambooHR to track time off. So we started looking at bamboo hr’s api, and saw that we could see who is out on what days. So I made a wrapper for the API and then we implemented it into our bot. So now we could retrieve data from the API, and use the data to determine if someone was out on that day.
To test this I had to mock the API data, because if I tested the actual API my tests would wait for the API to respond which slows down things… a lot. The data was being retrieved from a BambooInfoProvider class, this class connected to the API and retrieved data. My logic for automatically marking someone out used this class. For my tests I made a FakeBambooInfoProvider class, which had the same methods which just returned hard coded data.
Testing this slowed me down, but I needed to be slowed down and actually think about what I was doing. I have only properly got into the habit of testing the past couple of months and its so nice being confident in the code I write.