diff --git a/lib/shoulda/matchers/active_record/association_matcher.rb b/lib/shoulda/matchers/active_record/association_matcher.rb index 032009dc..98ee0acb 100644 --- a/lib/shoulda/matchers/active_record/association_matcher.rb +++ b/lib/shoulda/matchers/active_record/association_matcher.rb @@ -246,9 +246,13 @@ module Shoulda # :nodoc: reflection.options[:inverse_of] ) end - fk_reflection.respond_to?(:foreign_key) ? - fk_reflection.foreign_key : - fk_reflection.primary_key_name + if fk_reflection + fk_reflection.respond_to?(:foreign_key) ? + fk_reflection.foreign_key : + fk_reflection.primary_key_name + else + nil + end end def through? diff --git a/spec/shoulda/active_record/association_matcher_spec.rb b/spec/shoulda/active_record/association_matcher_spec.rb index 1a91f182..424241f5 100644 --- a/spec/shoulda/active_record/association_matcher_spec.rb +++ b/spec/shoulda/active_record/association_matcher_spec.rb @@ -240,6 +240,25 @@ describe Shoulda::Matchers::ActiveRecord::AssociationMatcher do Parent.new.should_not @matcher.class_name('Node') end + it "should accept an association with a nonstandard reverse foreign key, using :inverse_of" do + define_model :child, :ancestor_id => :integer, :adopted => :boolean do + belongs_to :ancestor, :inverse_of => :children, :class_name => :Parent + end + define_model :parent do + has_many :children, :inverse_of => :ancestor + end + Parent.new.should @matcher + end + + it "should reject an association with a nonstandard reverse foreign key, if :inverse_of is not correct" do + define_model :child, :mother_id => :integer, :adopted => :boolean do + belongs_to :mother, :inverse_of => :children, :class_name => :Parent + end + define_model :parent do + has_many :children, :inverse_of => :ancestor + end + Parent.new.should_not @matcher + end end context "have_one" do