【问题标题】:Unit testing a module that is included in ActiveRecord models对 ActiveRecord 模型中包含的模块进行单元测试
【发布时间】:2011-07-11 23:47:18
【问题描述】:

我有一个这样的模块(但更复杂):

module Aliasable 
  def self.included(base)
    base.has_many :aliases, :as => :aliasable
  end
end

我包含在几个模型中。目前为了测试,我制作了另一个模块,如下所示,我只是将其包含在测试用例中

module AliasableTest 
  def self.included(base)
    base.class_exec do 
      should have_many(:aliases)
    end
  end
end

问题是如何单独测试这个模块?或者上述方式是否足够好。似乎有更好的方法来做到这一点。

【问题讨论】:

    标签: ruby-on-rails-3 unit-testing shoulda


    【解决方案1】:

    首先,self.included 不是描述模块的好方法,class_exec 使事情变得不必要地复杂化。相反,您应该extend ActiveSupport::Concern,如:

    module Phoneable
      extend ActiveSupport::Concern
    
      included do
        has_one :phone_number
        validates_uniqueness_of :phone_number
      end
    end
    

    您没有提到您正在使用什么测试框架,但 RSpec 完全涵盖了这种情况。试试这个:

    shared_examples_for "a Phoneable" do
      it "should have a phone number" do
        subject.should respond_to :phone_number
      end
    end
    

    假设您的模型如下所示:

    class Person              class Business
      include Phoneable         include Phoneable
    end                       end
    

    然后,在您的测试中,您可以:

    describe Person do
      it_behaves_like "a Phoneable"      # reuse Phoneable tests
    
      it "should have a full name" do
        subject.full_name.should == "Bob Smith"
      end
    end
    
    describe Business do
      it_behaves_like "a Phoneable"      # reuse Phoneable tests
    
      it "should have a ten-digit tax ID" do
        subject.tax_id.should == "123-456-7890"
      end
    end
    

    【讨论】:

    • 谢谢,这非常有帮助。您知道使用 Test::Unit (和应该)的正确方法吗?
    • 据我所知,Test::Unit 没有类似的设施。当然,在这个例子中,你总是可以只创建一个像 PhoneableTests 这样的模块,然后通过包含它来重用它。
    • 我会将此标记为正确答案,然后我可能会问一个关于 shoulda 的不同问题,或者我应该跳上 RSpec 乐队。
    猜你喜欢
    • 2018-04-19
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    相关资源
    最近更新 更多