Permalink
Browse files

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
  • Loading branch information...
1 parent 0cd5859 commit fa37ef07af6c1a36da12c26f7ec2afc6b0e2499e tsaleh committed May 1, 2008
Showing with 19 additions and 8 deletions.
  1. +7 −8 lib/shoulda/active_record_helpers.rb
  2. +12 −0 test/rails_root/db/migrate/008_create_dogs_fleas.rb
View
15 lib/shoulda/active_record_helpers.rb
@@ -415,23 +415,22 @@ def should_have_one(*associations)
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
View
12 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

0 comments on commit fa37ef0

Please sign in to comment.