Shoulda matchers have_many with custom relation name
Asked Answered
S

1

6

How do I test this ActiveRecord relation using shoulda matchers?

Models

class User < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :author, class_name: 'User'
end

Test

describe User do
  it { should have_many(:articles) }
end

I'm getting the following error:

1) User should have many articles
     Failure/Error: it { should have_many(:articles) }
       Expected User to have a has_many association called articles (Article does not have a user_id foreign key.)
     # ./spec/models/user_spec.rb:4:in `block (2 levels) in <top (required)>'

So it obviously expects relation field to be named user_id because of User class name. I expect there has to be some test method that can be used to override this expectation like

it { should have_many(:articles).as(:owner) }

But I can't find anything like it. Am I missing something obvious?

Sole answered 9/2, 2014 at 10:24 Comment(0)
C
9

shoulda matchers includes a .with_foreign_key() option.

https://github.com/thoughtbot/shoulda-matchers#have_many

So in your example:

describe User do
  it { should have_many(:articles).with_foreign_key('author_id') }
end

Which is how your model should, I believe:

class User < ActiveRecord::Base
  has_many :articles, foreign_key: "author_id"
end
Chiropractic answered 9/2, 2014 at 12:5 Comment(1)
Spot on! I tried with_foreign_key before, but didn't know I had to define it in User model too. I thought ActiveRecord would know it by reading Article model. Now it passes, thanks a lot!Jocasta

© 2022 - 2024 — McMap. All rights reserved.