From 102fe37adc9a9b2c23132791bf16c0ff13553b3b Mon Sep 17 00:00:00 2001 From: Tammer Saleh Date: Sat, 26 Apr 2008 17:32:16 -0400 Subject: [PATCH] added should_have_indices to test for database indices --- lib/shoulda/active_record_helpers.rb | 20 +++++++++++++++++++ .../rails_root/db/migrate/001_create_users.rb | 4 ++++ test/unit/user_test.rb | 3 +++ 3 files changed, 27 insertions(+) diff --git a/lib/shoulda/active_record_helpers.rb b/lib/shoulda/active_record_helpers.rb index 138d415..6aa94f9 100644 --- a/lib/shoulda/active_record_helpers.rb +++ b/lib/shoulda/active_record_helpers.rb @@ -522,6 +522,26 @@ def should_have_db_column(name, opts = {}) end end end + + # Ensures that there are DB indices on the given columns or tuples of columns. + # Also aliased to should_have_index for readability + # + # should_have_indices :email, :name, [:commentable_type, :commentable_id] + # should_have_index :age + # + def should_have_indices(*columns) + table = model_class.name.tableize + indices = ::ActiveRecord::Base.connection.indexes(table).map(&:columns) + + columns.each do |column| + should "have index on #{table} for #{column.inspect}" do + columns = [column].flatten.map(&:to_s) + assert_contains(indices, columns) + end + end + end + + alias_method :should_have_index, :should_have_indices # Ensures that the model cannot be saved if one of the attributes listed is not accepted. # diff --git a/test/rails_root/db/migrate/001_create_users.rb b/test/rails_root/db/migrate/001_create_users.rb index 3c6423e..00221d0 100644 --- a/test/rails_root/db/migrate/001_create_users.rb +++ b/test/rails_root/db/migrate/001_create_users.rb @@ -5,6 +5,10 @@ def self.up t.column :email, :string t.column :age, :integer end + add_index :users, :email + add_index :users, :name + add_index :users, :age + add_index :users, [:email, :name] end def self.down diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index 8d278c3..ff1a57e 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -8,6 +8,9 @@ class UserTest < Test::Unit::TestCase should_have_one :address + should_have_indices :email, :name, [:email, :name] + should_have_index :age + should_not_allow_values_for :email, "blah", "b lah" should_allow_values_for :email, "a@b.com", "asdf@asdf.com" should_ensure_length_in_range :email, 1..100