Testing Rails Model Concerns

When I first started using model concerns I struggled with how I could test the functionality of the concern, without having to replicate the tests across all models. Here I show you how I decided to test model concerns. It may be controversial, so buckle up. What are Model Concerns? Model concerns are an interesting concept that — if I recall correctly— debuted with Rails 4. They allow a developer to refactor common functionality out from various models and centralize it into a module, called a concern. A non-contrived example of this shows how several of my models can be deactivated at any time. ...

March 12, 2020 · 4 min · 747 words · Scott Brown

A Refactoring Story in Four Parts

I recently tweeted about how people new to programming, or companies that look for candidates and give them programming tests, don’t understand that the first code one writes is just a draft. It can take several edits (so-called “refactors”) to tease out a good, workable, testable, and ultimately simple solution. So here’s a story of how I recently refactored my code 3 times before arriving at a final solution. This happened over the span of a day as I thought about and shaped the code into a format that can be easily tested and understood by others. The code is from a private project, so I am only presenting snippets here and some of the package names and variables have been changed for privacy. ...

October 11, 2019 · 7 min · 1370 words · Scott Brown

Refactoring Rails into Service Objects

One of the things that I dislike about Rails is how some actions feel untestable. Take, for example, the act of grabbing the current user. This is bog-standard code that you’d see in a lot of Rails tutorials and people’s codebases. What I don’t like about it is that the current_user method is not easily testable. Heck, which test file do you put the tests in? ...

October 28, 2013 · 3 min · 529 words · Scott Brown