Using rspec to test a named_scope in Ruby on Rails

Posted on 16 July 2010

When testing a named_scope it's important to test the expected behaviour of the method, not how it's implemented, as this will allow you to re-factor your code using the test as an indicator that the re-factor was successful.

So in your model you might have...

class User < ActiveRecord::Base
    named_scope :active, :conditions => ["active = ?", true]
end

In your model spec I'd then have...

describe User, "::active" do
    it "includes users that are active" do
        @user = Factory(:user, :active => true)
        User.active.should include(@user)
    end

    it "excludes users that are not active" do
        @user = Factory(:user, :active => false)
        User.active.should_not include(@user)
    end
end

The key thing here is that we're not actually calling named_scope, we could change the method to be a regular class method if we wanted and the test would still pass.

It may be a good idea to check that the model has the method defined like so...

User.should respond_to(:active)

Got something to say?