Łukasz Kazimierz Bandzarewicz

@lucassus

Testing Named Scopes in Ruby on Rails 3.x

The code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Topic < ActiveRecord::Base
  STATUS_PENDING = 'pending'
  STATUS_ACCEPTED = 'accepted'
  STATUS_DONE = 'done'
  STATUSES = [STATUS_PENDING, STATUS_ACCEPTED, STATUS_DONE].freeze

  ## Scopes
  default_scope :order => 'created_at DESC'
  # statuses
  scope :pending, where(:status => STATUS_PENDING)
  scope :accepted, where(:status => STATUS_ACCEPTED)
  scope :done, where(:status => STATUS_DONE)
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
describe Topic do

  describe "scopes" do
    describe :default do
      specify { Cse::Topic.scoped.arel.orders.should == ['created_at DESC'] }
    end

    describe "statuses" do
      Cse::Topic::STATUSES.each do |status|
        describe status do
          specify { Cse::Topic.send(status).where_values_hash.should == { :status => status } }
        end
      end
    end
  end

end