shoulda-matchers: Has many through association: undefined method `klass' for nil:NilClass
Hi!
I have an Subject model which should have many Photos through SubjectPhotoAssignments. When I test this, I get undefined method 'klass' for nil:NilClass
. Here is my setup:
class Subject < ActiveRecord::Base
belongs_to :project, touch: true
has_many :photos, through: :subject_photo_assignments
end
class SubjectPhotoAssignment < ActiveRecord::Base
belongs_to :photo
belongs_to :subject, touch: true
end
class Photo < ActiveRecord::Base
belongs_to :project, touch: true
has_many :album_photo_assignments
has_many :subject_photo_assignments
end
Here is the failing test:
RSpec.describe Subject, type: :model do
it { should have_many(:photos).through(:subject_photo_assignments) }
end
2) Subject should have many photos through subject_photo_assignments
Failure/Error: it { should have_many(:photos).through(:subject_photo_assignments) }
NoMethodError:
undefined method `klass' for nil:NilClass
What am I doing wrong? Any help is greatly appreciated. Let me know if more context would be helpful.
I’m using v2.7.0
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Reactions: 1
- Comments: 15
You’re saying that
Subject.has_many :photos, through: :subject_photo_assignments
, but you don’t have a:subject_photo_assignments
association.Ideally, we should probably have a check to ensure that your
through
association exists. But that’s why you’re getting an error.I added the
:subject_photo_assignments
association and the tests pass. For some reason I was thinking that argument was specifying the join table, not another association. Thank you very much for clearing up my blunder!Feel free to close the issue, unless you want to keep it open for adding a different error message.
I can verify that the reported issue has been fixed in the version
4.4.1
, so we can close this issue for now.Before:
After:
Error text differs as i’m using rails
6.1.0.alpha