Testing Rails 3 scopes revisited

| Posted: - Last updated:
| Tagged ruby on rails rails rspec rails3 scope named_scope
| ~300wrds (~2min)

In my previous article I told you about how I like to tests my scope. There was a fair amount of criticism on that post and after considering it all (and hearing Corey Haines' talk on Arrrrcamp last friday), I’m convinced it’s the wrong path.

In essence Rails allows you to create a scope to generate a custom database query for you. Now, if you only test your configuration of Rails (as I did in my previous post), you don’t know if that scope works or not. If a piece directly relies on your database, you must test it against your database.

Also, your configuration may be correct, but what happens when you upgrade to a newer version of Rails or PostgreSQL? Does that configuration still work as advertised?

So, this is the proper way of testing your scopes:

class Post < ActiveRecord::Base
  scope :latest, order("created_at DESC")

describe Post do
  context 'scopes' do
    before(:all) do
      @first = FactoryGirl.create(:post, :created_at => 1.day.ago)
      @last  = FactoryGirl.create(:post, :created_at => 4.day.ago)

    it "should return posts in the correct order" do
      Post.latest.should == [@first, @last]

A note on speed

So, you now have to utilize the whole Rails stack and hit your database to perform this test, which is slow. But then you don’t upgrade Rails or your database very often, so you don’t have run this spec with every TDD Baby Step you take. (More on that in a later post.)

My site is free of ads and trackers. I record privacy-respecting usage statistics with Fathom.

Was this post helpful to you? Why not ☕ Buy me a coffee or use Brave Browser to send a tip.