单元测试ActiveRecord模型中包含的模块

时间:2011-07-11 23:47:18

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

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

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

问题是如何单独测试此模块?或者以上方式是否足够好。似乎可能有更好的方法。

1 个答案:

答案 0 :(得分:8)

首先,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