如何使用shoulda匹配器来测试多态分析?
我正在使用带有rails的shoulda-matcher,我正在创建一个名为“comments”的模型和另一个名为“post”的模型。 评论是多态的。
当我在post中使用shoulda匹配器进行测试时,就像这样
it {should have_many(:comments)}
得到这个消息
期望Post有一个名为comments的has_many关联(Comment没有post_id外键。)
在我的评论模型中,我有
belongs_to :commentable, :polymorphic => true
如何测试我的多态关联,以便post可以有很多注释?
ps the shoulda matcher文档说它支持多态关联。
你应该不需要在你的测试中做任何特殊的事情,它应该只是工作。 在您的post模型上,请确保您设置:as
选项:
has_many :comments, :as => :commentable
这将确保rails使用正确的列名为commentable_id
和commentable_type
而不是post_id
。