Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

fixed should_have_and_belong_to to test for the join table

  • Loading branch information...
commit 28d9140a7ea45f9a305b251a544ead425fcd58e4 1 parent 102fe37
Tammer Saleh authored
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
Please sign in to comment.
Something went wrong with that request. Please try again.