thoughtbot--shoulda-matchers/lib
Mauro George c0a1578435 Fail have_many :through when inverse is invalid
When used with a `:through` association where a corresponding
`belongs_to` association has not been set up on the inverse model, the
`have_many` matcher raises this error:

    Failures:

      1) User should have many projects through clients
         Failure/Error: it {  should have_many(:projects).through :clients }
         NoMethodError:
           undefined method `class_name' for nil:NilClass
         # /Users/<USER>/.rvm/gems/ruby-2.2.0/gems/activerecord-4.2.0/lib/active_record/reflection.rb:871:in `derive_class_name'
         # /Users/<USER>/.rvm/gems/ruby-2.2.0/gems/activerecord-4.2.0/lib/active_record/reflection.rb:147:in `class_name'
         # /Users/<USER>/.rvm/gems/ruby-2.2.0/gems/shoulda-matchers-2.8.0/lib/shoulda/matchers/active_record/association_matcher.rb:1067:in `rescue in class_exists?'
         # /Users/<USER>/.rvm/gems/ruby-2.2.0/gems/shoulda-matchers-2.8.0/lib/shoulda/matchers/active_record/association_matcher.rb:1064:in `class_exists?'
         # /Users/<USER>/.rvm/gems/ruby-2.2.0/gems/shoulda-matchers-2.8.0/lib/shoulda/matchers/active_record/association_matcher.rb:928:in `matches?'
         # ./spec/models/user_spec.rb:5:in `block (2 levels) in <top (required)>'

Fortunately, ActiveRecord has a `check_validity!` method we can call on
an association. For `:through` associations, this will run through a
litany of checks, one of which is to check for the inverse association,
which we want in this case. We rescue the error that is produced and
include this in the failure message.

Co-authored-by: Elliot Winkler <elliot.winkler@gmail.com>
2020-07-10 22:44:22 -06:00
..
shoulda Fail have_many :through when inverse is invalid 2020-07-10 22:44:22 -06:00
shoulda-matchers.rb Switched to allowing a more canonical require statement 2011-01-31 16:45:13 -05:00