关于ruby on rails:如何使用比对匹配器测试多态关联?

How to use shoulda matchers to test a polymorphic assoication?

我正在将raila-matchers与rails配合使用,并且正在创建一个名为" comments "的模型和另一个名为" post "的模型。注释是多态的。

当我在这样的帖子中与shoulda Matchers进行测试时

1
    it {should have_many(:comments)}

它收??到此消息

Expected Post to have a has_many
association called comments (Comment
does not have a post_id foreign key.)

在我的评论模型中,我有

1
  belongs_to :commentable, :polymorphic => true

如何测试我的多态关联,以便帖子可以有很多评论?

p.s。 Shoulda Matcher文档说它支持多态关联。


您不需要为should做任何特殊的测试,它就可以正常工作。在您的帖子模型上,请确保设置了:as选项:

1
has_many :comments, :as => :commentable

这将确保rails使用正确的列名称commentable_idcommentable_type而不是post_id