Testing ActiveRecord Finders
Learn about testing ActiveRecord finders, duplication finders, performance finders, readability finders, error finders, and compound matchers.
ActiveRecord finders
ActiveRecord provides a rich set of methods that are wrappers around SQL statements sent to our database. These methods are collectively referred to as finders. One great feature of ActiveRecord finders is that they can be composed, allowing us to express a compound statement like “bring me the most recently completed five large tasks” as Task.where(status: completed).order("completed_at DESC").where("size > 3").limit(5)
.
We can even compose the finders if we extract them to their own methods in pieces:
class Task < ActiveRecord::Basedef self.completedwhere(status: :completed)enddef self.largewhere("size > 3")enddef self.most_recentorder("completed_at DESC")enddef self.recent_done_and_largecompleted.large.most_recent.limit(5)endend
Being able to compose this logic is awesome.
Testing finder methods
Finder methods occupy an awkward place between methods we might write and Rails core features, leading to the question of how best to test them.
Here are some guidelines.
Be ...