How to test a scope in Rails 3

前端 未结 6 540
夕颜
夕颜 2020-12-24 14:16

What\'s the best way to test scopes in Rails 3. In rails 2, I would do something like:

Rspec:

it \'should have a top_level scope\' do
  Category.top         


        
6条回答
  •  清歌不尽
    2020-12-24 14:56

    Leaving the question of 'how-to-test' aside... here's how to achieve similar stuff in Rails3...

    In Rails3 named scopes are different in that they just generate Arel relational operators. But, investigate!

    If you go to your console and type:

    # All the guts of arel!
    Category.top_level.arel.inspect
    

    You'll see internal parts of Arel. It's used to build up the relation, but can also be introspected for current state. You'll notice public methods like #where_clauses and such.

    However, the scope itself has a lot of helpful introspection public methods that make it easier than directly accessing @arel:

    # Basic stuff:
    => [:table, :primary_key, :to_sql]
    
    # and these to check-out all parts of your relation:
    => [:includes_values, :eager_load_values, :preload_values,
        :select_values, :group_values, :order_values, :reorder_flag,
        :joins_values, :where_values, :having_values, :limit_value,
        :offset_value, :readonly_value, :create_with_value, :from_value]
    
    # With 'where_values' you can see the whole tree of conditions:
    Category.top_level.where_values.first.methods - Object.new.methods
    => [:operator, :operand1, :operand2, :left, :left=, 
        :right, :right=, :not, :or, :and, :to_sql, :each]
    
    # You can see each condition to_sql
    Category.top_level.where_values.map(&:to_sql)
    => ["`categories`.`parent_id` IS NULL"]
    
    # More to the point, use #where_values_hash to see rails2-like :conditions hash:
    Category.top_level.where_values_hash
    => {"parent_id"=>nil}
    

    Use this last one: #where_values_hash to test scopes in a similar way to #proxy_options in Rails2....

提交回复
热议问题