Last updated

Properly testing Rails 3 scopes

The content of this post is no longer correct. Please read this article for details.

Testing scopes has always felt a bit weird to me. Normally I’d do something like this:

 1class Post < ActiveRecord::Base
 2  scope :published, where(:published => true)
 3  scope :latest, order("created_at DESC")
 4end
 5
 6describe Post do
 7  context 'scopes' do
 8    before(:all) do
 9      @first = FactoryGirl.create(:post, :created_at => 1.day.ago, :published => true)
10      @last  = FactoryGirl.create(:post, :created_at => 4.day.ago, :published => false)
11    end
12
13    it "should only return published posts" do
14      Post.published.should == [@first]
15    end
16
17    it "should return posts in the correct order" do
18      Post.latest.should == [@first, @last]
19    end
20  end
21end

This test is okay. It tests if the named scope does what it needs to do. And there’s also the problem. Scopes are part of ActiveRecord and are already extensively tested there. All we need to do is check if we configure the scope correctly.

What we need is a way to inspect what where and order rules are set for a particular scope and make sure those are the correct ones. We can then trust ActiveRecord to keep its promise to execute the proper SQL query for us.

Here’s another test that utilizes some Rails 3 methods you may not have heard of before.

 1describe Post do
 2  context 'scopes' do
 3    it "should only return published posts" do
 4      Post.published.where_values_hash.should == {:published => true}
 5    end
 6
 7    it "should return posts in the correct order" do
 8      Post.latest.order_values.should == ["created_at DESC"]
 9    end
10  end
11end

The where_values_hash and order_values allow you to inspect what a scopes doing. By writing your test this way you achieve two import goals:

  1. You test your code (instead of the ActiveRecord)
  2. You don’t use the database, which is a significant speed boost

Happy testing to you all!