Ruby on rails 3 单元测试ActiveRecord模型中包含的模块
我有这样一个模块(但更复杂): 我把它包括在几个模型中。目前,为了进行测试,我制作了另一个模块,如下所示,我只是将其包含在测试用例中Ruby on rails 3 单元测试ActiveRecord模型中包含的模块,ruby-on-rails-3,unit-testing,shoulda,Ruby On Rails 3,Unit Testing,Shoulda,我有这样一个模块(但更复杂): 我把它包括在几个模型中。目前,为了进行测试,我制作了另一个模块,如下所示,我只是将其包含在测试用例中 module AliasableTest def self.included(base) base.class_exec do should have_many(:aliases) end end end 问题是我如何单独测试这个模块?或者上述方法是否足够好。似乎有更好的方法可以做到这一点。首先,self.included
module AliasableTest
def self.included(base)
base.class_exec do
should have_many(:aliases)
end
end
end
问题是我如何单独测试这个模块?或者上述方法是否足够好。似乎有更好的方法可以做到这一点。首先,
self.included
不是描述模块的好方法,而且class\u 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
谢谢,这非常有帮助。您知道使用Test::Unit(和shoulda)的正确方法吗?据我所知,Test::Unit没有类似的功能。当然,在本例中,您可以创建一个类似于
PhoneableTests
的模块,然后通过包含该模块来重用它。我会将此标记为正确答案,然后我可能会问另一个关于shoulda的问题,或者我应该加入RSpec的行列。
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