1
0
Fork 0
mirror of https://github.com/thoughtbot/shoulda-matchers.git synced 2022-11-09 12:01:38 -05:00

converting should_have_index to use have_index matcher

This commit is contained in:
Dan Croak 2009-01-25 16:57:05 -05:00 committed by Joe Ferris
parent f1ec3e2113
commit 4512a9a8f6
3 changed files with 25 additions and 28 deletions

View file

@ -459,19 +459,12 @@ module Shoulda # :nodoc:
#
def should_have_indices(*columns)
unique = get_options!(columns, :unique)
table = model_class.table_name
indices = ::ActiveRecord::Base.connection.indexes(table)
index_types = { true => "unique", false => "non-unique" }
index_type = index_types[unique] || "an"
klass = model_class
columns.each do |column|
should "have #{index_type} index on #{table} for #{column.inspect}" do
columns = [column].flatten.map(&:to_s)
index = indices.detect {|ind| ind.columns == columns }
assert index, "#{table} does not have an index for #{column.inspect}"
if [true, false].include?(unique)
assert_equal unique, index.unique, "Expected #{index_type} index but was #{index_types[index.unique]}."
end
matcher = have_index(column).unique(unique)
should matcher.description do
assert_accepts(matcher, klass.new)
end
end
end

View file

@ -10,14 +10,14 @@ module Shoulda # :nodoc:
# Example:
# it { should have_index(:ssn).unique(true) }
#
def have_index(index)
HaveIndexMatcher.new(:have_index, index)
def have_index(columns)
HaveIndexMatcher.new(:have_index, columns)
end
class HaveIndexMatcher # :nodoc:
def initialize(macro, index)
def initialize(macro, columns)
@macro = macro
@index = normalize_index_to_array(index)
@columns = normalize_columns_to_array(columns)
end
def unique(unique)
@ -39,7 +39,7 @@ module Shoulda # :nodoc:
end
def description
"have index named #{@column}"
"have a #{index_type} index on columns #{@columns}"
end
protected
@ -53,33 +53,41 @@ module Shoulda # :nodoc:
if matched_index.unique == @unique
true
else
@missing = "#{model_class} has an index named #{matched_index.name} " <<
@missing = "#{table_name} has an index named #{matched_index.name} " <<
"of unique #{matched_index.unique}, not #{@unique}."
false
end
end
def matched_index
indexes.detect { |each| each.columns == @index }
indexes.detect { |each| each.columns == @columns }
end
def model_class
@subject.class
end
def table_name
model_class.table_name
end
def indexes
::ActiveRecord::Base.connection.indexes(model_class.table_name)
::ActiveRecord::Base.connection.indexes(table_name)
end
def expectation
expected = "#{model_class.name} to #{description}"
end
def normalize_index_to_array(index)
if index.class == Array
index.collect { |each| each.to_s }
def index_type
@unique ? "unique" : "non-unique"
end
def normalize_columns_to_array(columns)
if columns.class == Array
columns.collect { |each| each.to_s }
else
[index.to_s]
[columns.to_s]
end
end
end

View file

@ -1,9 +1,5 @@
require 'fileutils'
require 'rubygems'
require 'quietbacktrace'
require 'redgreen'
# Load the environment
ENV['RAILS_ENV'] = 'test'