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

mik*_*ike 5 unit-testing shoulda ruby-on-rails-3

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

module Aliasable 
  def self.included(base)
    base.has_many :aliases, :as => :aliasable
  end
end
Run Code Online (Sandbox Code Playgroud)

我包含在几个模型中.目前我正在进行测试,我将制作另一个模块,我将其包含在测试用例中

module AliasableTest 
  def self.included(base)
    base.class_exec do 
      should have_many(:aliases)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*lla 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
Run Code Online (Sandbox Code Playgroud)

您没有提到您正在使用的测试框架,但RSpec正好涵盖了这种情况.试试这个:

shared_examples_for "a Phoneable" do
  it "should have a phone number" do
    subject.should respond_to :phone_number
  end
end
Run Code Online (Sandbox Code Playgroud)

假设您的模型看起来像:

class Person              class Business
  include Phoneable         include Phoneable
end                       end
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)