From fa37ef07af6c1a36da12c26f7ec2afc6b0e2499e Mon Sep 17 00:00:00 2001 From: tsaleh Date: Thu, 1 May 2008 13:49:38 +0000 Subject: [PATCH] fixed should_have_and_belong_to to test for the join table git-svn-id: https://svn.thoughtbot.com/plugins/shoulda/trunk@488 7bbfaf0e-4d1d-0410-9690-a8bb5f8ef2aa --- lib/shoulda/active_record_helpers.rb | 15 +++++++-------- .../db/migrate/008_create_dogs_fleas.rb | 12 ++++++++++++ 2 files changed, 19 insertions(+), 8 deletions(-) create mode 100644 test/rails_root/db/migrate/008_create_dogs_fleas.rb diff --git a/lib/shoulda/active_record_helpers.rb b/lib/shoulda/active_record_helpers.rb index 6aa94f94..8133755d 100644 --- a/lib/shoulda/active_record_helpers.rb +++ b/lib/shoulda/active_record_helpers.rb @@ -415,23 +415,22 @@ module ThoughtBot # :nodoc: end end - # Ensures that the has_and_belongs_to_many relationship exists. + # Ensures that the has_and_belongs_to_many relationship exists, and that the join + # table is in place. # # should_have_and_belong_to_many :posts, :cars # - # NOTE: One thing this macro should test, but doesn't is that the join - # table exists in the DB. Please contact the author if you know of a DB - # agnostic way of introspecting on the current schema. def should_have_and_belong_to_many(*associations) get_options!(associations) klass = model_class associations.each do |association| should "should have and belong to many #{association}" do - assert klass.reflect_on_association(association), - "#{klass.name} does not have any relationship to #{association}" - assert_equal :has_and_belongs_to_many, - klass.reflect_on_association(association).macro + reflection = klass.reflect_on_association(association) + assert reflection, "#{klass.name} does not have any relationship to #{association}" + assert_equal :has_and_belongs_to_many, reflection.macro + table = reflection.options[:join_table] + assert ::ActiveRecord::Base.connection.tables.include?(table), "table #{table} doesn't exist" end end end diff --git a/test/rails_root/db/migrate/008_create_dogs_fleas.rb b/test/rails_root/db/migrate/008_create_dogs_fleas.rb new file mode 100644 index 00000000..98555aec --- /dev/null +++ b/test/rails_root/db/migrate/008_create_dogs_fleas.rb @@ -0,0 +1,12 @@ +class CreateDogsFleas < ActiveRecord::Migration + def self.up + create_table :dogs_fleas do |t| + t.integer :dog_id + t.integer :flea_id + end + end + + def self.down + drop_table :dogs_fleas + end +end