Skip to content

Commit

Permalink
added should_have_indices to test for database indices
Browse files Browse the repository at this point in the history
  • Loading branch information
Tammer Saleh committed Apr 26, 2008
1 parent 2c975a1 commit 102fe37
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/shoulda/active_record_helpers.rb
Expand Up @@ -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.
#
Expand Down
4 changes: 4 additions & 0 deletions test/rails_root/db/migrate/001_create_users.rb
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions test/unit/user_test.rb
Expand Up @@ -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
Expand Down

0 comments on commit 102fe37

Please sign in to comment.