-
-
Notifications
You must be signed in to change notification settings - Fork 909
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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>
- Loading branch information
1 parent
f50f70e
commit c0a1578
Showing
4 changed files
with
68 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters