Skip to content

testing named scopes

Named scopes are a nice feature that came out in rails 2.1, however, testing them is not very obvious.

Say we have a named scope in our member object which looks like this:

class Member < ActiveRecord::Base
  named_scope :active, {:conditions => {:status => Member::STATUS_ACTIVE}}

There are 2 things we need to do to test them.

First would be to make sure that the conditions are the same as we think they are. This one is open for debate a bit as it is somewhat tying the implementation directly to the test.

Second, we actually have to USE the scope. Just calling does not actually use the scope. This is because named scopes can be cascaded. If I had recent scope on a member that only showed me those that signed up recently, I could actually do, and it would not execute against database, it would just nest the conditions.

So how do I use the scope? Use any collection method on them. I like size, but I’m completely open to suggestions. So below is how I am testing named scopes.

class MemberTest < ActiveRecord::TestCase
  context 'named scope active' do
    setup do
      @scoped_find =

    should "have condition active" do
      expected_conditions  = {:conditions => ["member.status == #{Member::STATUS_ACTIVE}"]}
      assert_equal expected_conditions, @scoped_find.proxy_options

    should "have results" do

The first test does part 1, the 2nd, part 2.

Post a Comment

Your email is never published nor shared.