本文介绍了如何使用Shoulda Matchers测试多态关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using shoulda-matchers with rails and I'm creating a model called "comments" and another model called "post". Comments is polymorphic.

当我在这样的帖子中与shoda匹配器一起测试时

When I test with shoulda matchers in post like this

    it {should have_many(:comments)}

它收到此消息

在我的评论模型中,我有

In my comment model I have

  belongs_to :commentable, :polymorphic => true

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

How can I test my polymorphic association so that a post can have many comments?

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

p.s. the shoulda matcher documentation said it supports polymorphic associations.

推荐答案

对于should它应该可以正常工作,您不需要在测试中做任何特殊的事情.确保在您的帖子模型上设置:as选项:

You shouldn't need to do anything special in your test for should it should just work. On your post model ensure sure you set the :as option:

has_many :comments, :as => :commentable

这将确保Rails使用正确的列名commentable_idcommentable_type而不是post_id.

That will ensure rails uses the proper column names commentable_id and commentable_type rather than post_id.

这篇关于如何使用Shoulda Matchers测试多态关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 10:56