From fdde3a50a4cec6276136e5eb5156543dba42075e Mon Sep 17 00:00:00 2001 From: Jacob Morris Date: Wed, 23 Jul 2014 17:26:15 -0600 Subject: [PATCH] Explicitly test custom `:join_table` option #547 Some developers might want to pass a :join_table option to their HABTM association declarations (e.g., `has_and_belongs_to_many :posts, join_table: :users_and_their_posts). Those same developers, may want to explicitly test the existence of the join table. Make this possible. --- .../active_record/association_matcher.rb | 4 ++ .../active_record/association_matcher_spec.rb | 42 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/lib/shoulda/matchers/active_record/association_matcher.rb b/lib/shoulda/matchers/active_record/association_matcher.rb index f791ca57..3e742b6f 100644 --- a/lib/shoulda/matchers/active_record/association_matcher.rb +++ b/lib/shoulda/matchers/active_record/association_matcher.rb @@ -905,6 +905,10 @@ module Shoulda self end + def join_table(join_table_name) + self + end + def description description = "#{macro_description} #{name}" description += " class_name => #{options[:class_name]}" if options.key?(:class_name) diff --git a/spec/unit/shoulda/matchers/active_record/association_matcher_spec.rb b/spec/unit/shoulda/matchers/active_record/association_matcher_spec.rb index da8f20ba..d2998020 100644 --- a/spec/unit/shoulda/matchers/active_record/association_matcher_spec.rb +++ b/spec/unit/shoulda/matchers/active_record/association_matcher_spec.rb @@ -886,6 +886,48 @@ describe Shoulda::Matchers::ActiveRecord::AssociationMatcher, type: :model do end.to fail_with_message_including('missing columns: person_id, relative_id') end + it "rejects an association with a bad :join_table option" do + define_model :relative + join_table_name = 'people_and_their_families' + + define_model :person do + has_and_belongs_to_many( + :relatives, join_table: join_table_name + ) + end + + create_table("people_relatives", id: false) do |t| + t.references :person + t.references :relative + end + + expect do + expect(Person.new).to( + have_and_belong_to_many(:relatives).join_table(join_table_name) + ) + end.to fail_with_message_including("#{join_table_name} doesn't exist") + end + + it "accepts an association with a valid :join_table option" do + define_model :relative + join_table_name = 'people_and_their_families' + + define_model :person do + has_and_belongs_to_many( + :relatives, join_table: join_table_name + ) + end + + create_table(join_table_name, id: false) do |t| + t.references :person + t.references :relative + end + + expect(Person.new).to( + have_and_belong_to_many(:relatives).join_table(join_table_name) + ) + end + context 'using a custom foreign key' do it 'rejects an association with a join table with incorrect columns' do define_model :relative