如何在 Rails 3 中测试范围 [英] How to test a scope in Rails 3

查看:33
本文介绍了如何在 Rails 3 中测试范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 3 中测试作用域的最佳方法是什么.在 Rails 2 中,我会这样做:

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_level.proxy_options.should == {:conditions => {:parent_id => nil}}
end

这在 rails 3 中失败,出现[]:ActiveRecord::Relation 的未定义方法`proxy_options'"错误.

This fails in rails 3 with a "undefined method `proxy_options' for []:ActiveRecord::Relation" error.

人们如何测试范围是否指定了正确的选项?我看到您可以检查 arel 对象,并可能对此有一些期望,但我不确定这样做的最佳方法是什么.

How are people testing that a scope is specified with the correct options? I see you could examine the arel object and might be able to make some expectations on that, but I'm not sure what the best way to do it would be.

推荐答案

将如何测试"的问题搁置一旁...这里是如何在 Rails3 中实现类似的东西...

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

在 Rails3 中命名作用域的不同之处在于它们只生成 Arel 关系运算符.但是,调查!

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

您将看到 Arel 的内部部件.它用于建立关系,但也可以内省当前状态.您会注意到诸如#where_clauses 之类的公共方法.

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.

然而,作用域本身有很多有用的自省公共方法,比直接访问@arel 更容易:

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}

使用最后一个:#where_values_hash 以与 Rails2 中的 #proxy_options 类似的方式测试作用域....

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

这篇关于如何在 Rails 3 中测试范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆