How to test a scope in Rails 3

前端 未结 6 535
夕颜
夕颜 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:39

    Quickly Check the Clauses of a Scope

    I agree with others here that testing the actual results you get back and ensuring they are what you expect is by far the best way to go, but a simple check to ensure that a scope is adding the correct clause can also be useful for faster tests that don't hit the database.

    You can use the where_values_hash to test where conditions. Here's an example using Rspec:

    it 'should have a top_level scope' do
      Category.top_level.where_values_hash.should eq {"parent_id" => nil}
    end
    

    Although the documentation is very slim and sometimes non-existent, there are similar methods for other condition-types, such as:

    order_values

    Category.order(:id).order_values
    # => [:id]
    

    select_values

    Category.select(:id).select_values
    # => [:id]
    

    group_values

    Category.group(:id).group_values
    # => [:id]
    

    having_values

    Category.having(:id).having_values
    # => [:id]
    

    etc.

    Default Scope

    For default scopes, you have to handle them a little differently. Check this answer out for a better explanation.

提交回复
热议问题