Shoulda-matchers: undefined method `reflect_on_association' for Class:Class

Created on 13 May 2018  路  3Comments  路  Source: thoughtbot/shoulda-matchers

# models/album.rb
class Album < ApplicationRecord
  belongs_to :user
RSpec.describe Album, type: :model do
  subject { described_class }

  it { should belong_to(:user) }
     NoMethodError:
       undefined method `reflect_on_association' for Class:Class
     # /Users/aht/.rvm/gems/ruby-2.5.0@eschools/gems/shoulda-matchers-3.1.2/lib/shoulda/matchers/active_record/association_matchers/model_reflector.rb:21:in `reflect_on_association'
     # /Users/aht/.rvm/gems/ruby-2.5.0@eschools/gems/shoulda-matchers-3.1.2/lib/shoulda/matchers/active_record/association_matchers/model_reflector.rb:17:in `reflection'
     # /Users/aht/.rvm/gems/ruby-2.5.0@eschools/gems/shoulda-matchers-3.1.2/lib/shoulda/matchers/active_record/association_matcher.rb:883:in `reflection'
     # /Users/aht/.rvm/gems/ruby-2.5.0@eschools/gems/shoulda-matchers-3.1.2/lib/shoulda/matchers/active_record/association_matcher.rb:1060:in `association_exists?'
     # /Users/aht/.rvm/gems/ruby-2.5.0@eschools/gems/shoulda-matchers-3.1.2/lib/shoulda/matchers/active_record/association_matcher.rb:989:in `matches?'
     # ./spec/models/album_spec.rb:7:in `block (2 levels) in <top (required)>'

Rails 5.1.6
shoulda-matchers (3.1.2)

Most helpful comment

With your subject set to Album, the test you're essentially writing is:

it { expect(Album).to belong_to(:user) }

While this logically makes sense, this is not the intended usage of belong_to; your subject needs to return a new instance of Album instead. This is what RSpec does by default, so if you remove your subject entirely then it should work :)

All 3 comments

With your subject set to Album, the test you're essentially writing is:

it { expect(Album).to belong_to(:user) }

While this logically makes sense, this is not the intended usage of belong_to; your subject needs to return a new instance of Album instead. This is what RSpec does by default, so if you remove your subject entirely then it should work :)

ouch. Thanks.

No problem!

Was this page helpful?
0 / 5 - 0 ratings