How to use shoulda matchers to test a polymorphic association?
Asked Answered
L

1

18

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.

Legault answered 9/3, 2011 at 10:24 Comment(2)
What do you have on Post model?Affluent
I realise this is an old question but a solution was never posted. I asked the same question (stackoverflow.com/questions/18405058) and the solution was to run my migrations in the test database (doh!).Cheloid
G
11

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.

Giuseppinagiustina answered 17/7, 2011 at 16:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.