named_scope依赖于关联的存在是破坏测试

时间:2010-01-29 15:48:34

标签: ruby-on-rails unit-testing activerecord

用户模型:

class User < ActiveRecord::Base
  named_scope :clients, 
    :conditions => "roles_users.role_id = #{Role.find_by_name('client').id}"
end

测试时,抛出错误:

Called id for nil, which would mistakenly be 4 -- if you really wanted (etc.)

角色固定装置:

client:
  name: client
user:
  name: user

表观问题:Rails在加载灯具之前加载此类。当它加载类时,它会评估named_scope。那时没有任何角色,所以它会爆炸。

可能的解决方案:

named_scope :clients, 
  lambda { { :conditions => "roles_users.role_id = #{Role.named('client').id}" } }

然而,我对这个解决方案并不满意,因为它引入了额外的复杂性,并且可能是(小?)性能损失,只是为了使测试正常运行。我想要一个替代方案。你能帮忙吗?

1 个答案:

答案 0 :(得分:1)

您提出的解决方案是正确的解决方案。我还建议您将代码更改为:

named_scope :clients, lambda { { :conditions => ['roles_users.role_id = ?', Role.named('client').id } }

替代方案可能是:

named_scope :clients, :joins => :role, :conditions => ['roles.name = ?', 'client']

您可能还想考虑做:

named_scope :with_role, lambda { |r| { :conditions => ['roles_users.role_id = ?', r.id] } }

甚至(加分)

Role.find_by_name('client').users

无论如何,我希望这有帮助。