From c863f7e6f00103b95a5be8234a2db9eb9bfc0f4d Mon Sep 17 00:00:00 2001 From: Mike Bloy Date: Sun, 4 Mar 2012 00:33:14 -0600 Subject: [PATCH] association_matcher foreign_key refinement https://github.com/thoughtbot/shoulda-matchers/issues/66 has_many and has_one tests failed with the reverse association has a nonstandard name, (eg "belongs_to :author, :class_name => :User) corrected by having have_one and have_many association tests check for an :inverse_of on their association, and use the inverse relationship's foreign key info if it can be found --- .../matchers/active_record/association_matcher.rb | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/shoulda/matchers/active_record/association_matcher.rb b/lib/shoulda/matchers/active_record/association_matcher.rb index 911d8e27d..032009dc2 100644 --- a/lib/shoulda/matchers/active_record/association_matcher.rb +++ b/lib/shoulda/matchers/active_record/association_matcher.rb @@ -240,7 +240,15 @@ def associated_class end def foreign_key - reflection.respond_to?(:foreign_key) ? reflection.foreign_key : reflection.primary_key_name + fk_reflection = reflection + if [:has_one, :has_many].include?(@macro) && reflection.options.include?(:inverse_of) + fk_reflection = associated_class.reflect_on_association( + reflection.options[:inverse_of] + ) + end + fk_reflection.respond_to?(:foreign_key) ? + fk_reflection.foreign_key : + fk_reflection.primary_key_name end def through?