Posts

Showing posts from November, 2021

Ruby RSpec: Mocks, Doubles, and Spies with Constructor Injection

Inversion of Control (IOC) containers or Dependency Injection  is a common design pattern used to help engineers "inject" different instances of an object at runtime into services, controllers, or gateway classes. This concept is somewhat foreign to the Ruby on Rails community but valuable in some contexts. Most unit tests in RoR won't utilize mocks and stubs and instead opt for direct integration with the database. This article provides an alternative to integration testing by unit testing through constructor injection. In this example, we will test the business logic that operates between an API request and an external, third-party web service. I will note that this pattern forces developers to consider not using patterns like that in active record callbacks. The problem with callbacks is they are hard to test and can conflate what business rules exist in a domain context . Instead, you can move these operations into "service" classes . This enables future dev...