有効なユーザ
class User <ActiveRecord::Base
named_scope(:active,
{:condition=>["deleted = ?", false]})
end
describe “activeなユーザ” do
it “は全員削除されて*いない*こと” do
User.active.should be_all{|u| not u.deleted }
end
end
人気のあるユーザ
実行時にscopeの一部を指定
class User < ActiveRecord::Base
named_scope :active,
:condition=>["deleted = ?", false]
named_scope :hot,
Proc.new{|arg|
{:conditions=>[“popularity > ?”, arg],
:order =>"popularity DESC"}
}
end
14.
人気のあるユーザ
実行時にscopeの一部を指定
describe “人気度80以上のユーザ” do
before do
@users = User.hot(80)
end
it "のうちトップはdahliaであること" do
@users.first.should == users(:dahlia)
end
end
人気かつ有効なユーザ
crossover 2 scopes
describe "BAN! dahlia" do
before(:each) do
# dahliaの削除フラグを立てる つまり active usersの集合から外す
users(:dahlia).update_attribute(:deleted, true)
end
it "アクティブユーザで最も人気なのはcharlesであること" do
User.active.hot(80).first.should == users(:charles)
end
it "クエリ発行(select_all)は一回だけ呼ばれること" do
User.connection.should_receive(:select_all).once.and_return([])
User.hot(80).active.find(:all)
end
end
with_scopeで
書き直したイメージ
User.with_scope(
:find=>{:conditions=>[”popularity>?”, 80],
:order=>”popularity” }) do
User.with_scope(
:find=>{:conditons=>[“deleted=?”, false]}) do
User.find(:all).each{ ... }
end
end Rails2.xではこのままでは動きません