[rspec-users] testing named_scope

David Chelimsky dchelimsky at gmail.com
Mon Jan 18 05:17:32 EST 2010


On Mon, Jan 18, 2010 at 4:01 AM, Pat Maddox <mailinglists at patmaddox.com> wrote:
> On Jan 17, 2010, at 6:17 PM, Nin wrote:
> > Hi! I'm new to rspec and was wondering how named_scopes are usually
> > tested? Is it enough to test that it's defined? or do you need to test
> > the behavior as well? I've been reading around and this seems to be
> > the tester's choice, i just want to get people's opinion on this :D
>
> class User < ActiveRecord::Base
>  named_scope :admins, :conditions => {:admin => true}
> end
>
> describe User, "admins" do
>  it "should include users with admin flag" do
>    admin = User.create! :admin => true
>    User.admin.should include(admin)
>  end
>
>  it "should not include users without admin flag" do
>    admin = User.create! :admin => false
>    User.admin.should_not include(admin)
>  end
> end

Small style matter, but I've leaning towards more declarative sounding
example names:

describe User, ".admins" do
  it "includes users with admin flag" do
    admin = User.create! :admin => true
    User.admin.should include(admin)
  end

  it "excludes users without admin flag" do
    non_admin = User.create! :admin => false
    User.admin.should_not include(non_admin)
  end
end

class User < ActiveRecord::Base
  named_scope :admins, :conditions => {:admin => true}
end

We still have 'should' in the examples, but this produces more
'spec-like' output:

User.admins
  includes users with admin flag
  excludes users without admin flag

FWIW,
David


More information about the rspec-users mailing list