对 ActiveRecord 模型中包含的模块进行单元测试
我有一个像这样的模块(但更复杂):
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
问题是如何单独测试该模块?或者上面的方法已经足够好了。似乎可能有更好的方法来做到这一点。
I have a module like this (but more complicated):
module Aliasable
def self.included(base)
base.has_many :aliases, :as => :aliasable
end
end
which I include in several models. Currently for testing I make another module as below, which I just include in the test case
module AliasableTest
def self.included(base)
base.class_exec do
should have_many(:aliases)
end
end
end
The question is how do I go about testing this module in isolation? Or is the above way good enough. Seems like there is probably a better way to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,self.included 并不是描述模块的好方法,而 class_exec 则不必要地使事情变得复杂。相反,您应该
扩展 ActiveSupport::Concern
,如下所示:您没有提及您正在使用的测试框架,但 RSpec 恰好涵盖了这种情况。试试这个:
假设你的模型看起来像:
然后,在你的测试中,你可以这样做:
First off,
self.included
is not a good way to describe your modules, andclass_exec
is needlessly complicating things. Instead, you shouldextend ActiveSupport::Concern
, as in:You didn't mention what test framework you're using, but RSpec covers exactly this case. Try this:
Assuming your models look like:
Then, in your tests, you can do: