【问题标题】:Does testing Rails 3 Scopes make sense?测试 Rails 3 Scopes 有意义吗?
【发布时间】:2011-09-01 03:57:40
【问题描述】:

我有点伤心。 Rails 3 中 Scopes 的单元测试有意义吗?

一方面,我正在编写代码,我应该测试该代码。

但是,另一方面,基本上我所有的作用域实际上都是微不足道的。根据传递的参数检查一个变量几乎是我迄今为止最复杂的范围。

scope :author, proc { |author| where(:author_user_id => author }

该代码是微不足道的,并且或多或少包含在实际使用范围的函数中。

测试或不测试范围的最佳做法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 unit-testing named-scope


    【解决方案1】:

    David Chelimsky(Rspec 的创建者)在 Rspec Google Group 中提供了以下示例:

    describe User, ".admins" do 
      it "includes users with admin flag" do 
        admin = User.create! :admin => true 
        User.admin.should include(admin) 
      end
    
      it "excludes users without admin flag" do 
        non_admin = User.create! :admin => false 
        User.admin.should_not include(non_admin) 
      end 
    end
    
    class User < ActiveRecord::Base 
      named_scope :admins, :conditions => {:admin => true} 
    end 
    

    这显然与你的例子不同,但它应该让你知道如何去做。上下文的相关线程在这里:http://groups.google.com/group/rspec/browse_thread/thread/6706c3f2cceef97f

    【讨论】:

      【解决方案2】:

      如果您认为范围太简单而无法测试,您当然可以忽略它,但如果您正在考虑测试范围,我会告诉您查看 this answer 并专注于测试行为而不是代码本身。

      【讨论】:

      • 我想说你不应该测试范围实现,而是行为。 Here is the answer我会链接到。
      猜你喜欢
      • 2018-07-03
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 2010-10-31
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多