Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use shoulda matchers to test a polymorphic association?

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

When I test with shoulda matchers in post like this

    it {should have_many(:comments)}

it get this message

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

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. the shoulda matcher documentation said it supports polymorphic associations.

like image 200
user651339 Avatar asked Mar 09 '11 10:03

user651339


1 Answers

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

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

like image 68
JDutil Avatar answered Sep 20 '22 13:09

JDutil