...

/

Testing ActiveRecord Finders

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:

Press + to interact
class Task < ActiveRecord::Base
def self.completed
where(status: :completed)
end
def self.large
where("size > 3")
end
def self.most_recent
order("completed_at DESC")
end
def self.recent_done_and_large
completed.large.most_recent.limit(5)
end
end

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 ...