Sha256: 558c4dcedc479904d205d333ea5066e7fa5c6712dabe8913913cc6cd930335d3

Contents?: true

Size: 1.53 KB

Versions: 8

Compression:

Stored size: 1.53 KB

Contents

module SchemaPlus::IndexesMatchers

  class HaveIndex

    def initialize(expectation, options = {})
      set_required_columns(expectation)
      @unique = options.delete(:unique)
      @name   = options.delete(:name)
    end

    def matches?(model)
      @too_many = nil
      @model = model
      indexes = @model.indexes.select { |index| index.columns.to_set == @required_columns }
      if indexes.length > 1
        @too_many = indexes.length
        return false
      end
      index = indexes.first
      return index && (@unique ? index.unique : true) && (@name ? index.name == @name.to_s : true)
    end

    def failure_message(should_not = false)
      invert = should_not ? "not to" : "to"
      what = ""
      what += "unique " if @unique
      what += "named '{@name}'" if @name
      msg = "Expected #{@model.table_name} #{invert} contain one #{what}index on #{@required_columns.entries.inspect}"
      msg += "; found #{@too_many} indexes" if @too_many
      msg
    end

    def failure_message_when_negated
      failure_message(true)
    end

    def on(expectation)
      set_required_columns(expectation)
      self
    end

    private
    def set_required_columns(expectation)
      @required_columns = Array(expectation).collect(&:to_s).to_set
    end

  end

  def have_index(*expectation)
    options = expectation.extract_options!
    HaveIndex.new(expectation, options)
  end

  def have_unique_index(*expectation)
    options = expectation.extract_options!
    options[:unique] = true
    HaveIndex.new(expectation, options)
  end

end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
schema_plus_indexes-0.3.1 spec/support/matchers/have_index.rb
schema_plus_indexes-0.3.0 spec/support/matchers/have_index.rb
schema_plus_indexes-0.2.4 spec/support/matchers/have_index.rb
schema_plus_indexes-0.2.3 spec/support/matchers/have_index.rb
schema_plus_indexes-0.2.2 spec/support/matchers/have_index.rb
schema_plus_indexes-0.2.1 spec/support/matchers/have_index.rb
schema_plus_indexes-0.2.0 spec/support/matchers/have_index.rb
schema_plus_indexes-0.1.3 spec/support/matchers/have_index.rb