Rake Tasks Should Not Contain Business Logic
Learn why Rake tests should not contain the business logic of our Rails application.
We'll cover the following...
Guidelines for business logic in Rake tasks
All the reasons we’ve discussed about why business logic doesn’t go into controllers, jobs, or mailers apply to Rake tasks, too. It’s just not worth it. We end up having to test the Rake tasks—not an easy prospect, and we end up with code we may need elsewhere buried in some file in the lib/tasks
directory. Our Rake tasks should ideally be one line of code to trigger some business logic. If the logic is particularly esoteric to a one-off use case, it can be hard to figure out where it should go to avoid being mistakenly reused.
Let’s make two Rake tasks to demonstrate the subtleties of this guideline. Suppose we have a new status for widgets called “Legacy,” and we want any widget in “Approved” to be given the status “Legacy” if it’s been more than a year since its creation. We’ll run this task daily to automatically update the widgets.
Because this is our first task, let’s not worry about namespaces. We don’t have enough data about our needs to choose a good one and put it in lib/tasks
. We’ll call the task change_approved_widgets_to_legacy
. Because the actual code should not ...