ruby-on-rails-3 – 对ActiveRecord模型中包含的模块进行单元测
发布时间:2020-12-17 02:52:42 所属栏目:百科 来源:网络整理
导读:我有一个像这样的模块(但更复杂): module Aliasable def self.included(base) base.has_many :aliases,:as = :aliasable endend 我包含在几个模型中.目前我正在进行测试,我将制作另一个模块,我将其包含在测试用例中 module AliasableTest def self.included
我有一个像这样的模块(但更复杂):
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 问题是如何单独测试该模块?或者以上方式是否足够好.似乎有可能有更好的方法来做到这一点. 解决方法
首先,self.included不是描述模块的好方法,而class_exec不必要地使事情复杂化.相反,您应该扩展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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |