diff --git a/lib/shoulda/matchers/active_record/association_matcher.rb b/lib/shoulda/matchers/active_record/association_matcher.rb index 251c9049..e45c106c 100644 --- a/lib/shoulda/matchers/active_record/association_matcher.rb +++ b/lib/shoulda/matchers/active_record/association_matcher.rb @@ -68,6 +68,11 @@ module Shoulda # :nodoc: self end + def order(order) + @order = order + self + end + def matches?(subject) @subject = subject association_exists? && @@ -75,6 +80,7 @@ module Shoulda # :nodoc: foreign_key_exists? && through_association_valid? && dependent_correct? && + order_correct? && join_table_exists? end @@ -90,6 +96,7 @@ module Shoulda # :nodoc: description = "#{macro_description} #{@name}" description += " through #{@through}" if @through description += " dependent => #{@dependent}" if @dependent + description += " order => #{@order}" if @order description end @@ -159,6 +166,15 @@ module Shoulda # :nodoc: end end + def order_correct? + if @order.nil? || @order.to_s == reflection.options[:order].to_s + true + else + @missing = "#{@name} should be ordered by #{@order}" + false + end + end + def join_table_exists? if @macro != :has_and_belongs_to_many || ::ActiveRecord::Base.connection.tables.include?(join_table.to_s) diff --git a/spec/shoulda/active_record/association_matcher_spec.rb b/spec/shoulda/active_record/association_matcher_spec.rb index 828937e6..d91ae5a1 100644 --- a/spec/shoulda/active_record/association_matcher_spec.rb +++ b/spec/shoulda/active_record/association_matcher_spec.rb @@ -160,6 +160,23 @@ describe Shoulda::Matchers::ActiveRecord::AssociationMatcher do end Parent.new.should_not @matcher.dependent(:destroy) end + + it "should accept an association with a valid :order option" do + define_model :child, :parent_id => :integer + define_model :parent do + has_many :children, :order => :id + end + Parent.new.should @matcher.order(:id) + end + + it "should reject an association with a bad :order option" do + define_model :child, :parent_id => :integer + define_model :parent do + has_many :children + end + Parent.new.should_not @matcher.order(:id) + end + end context "have_one" do @@ -216,6 +233,23 @@ describe Shoulda::Matchers::ActiveRecord::AssociationMatcher do end Person.new.should_not @matcher.dependent(:destroy) end + + it "should accept an association with a valid :order option" do + define_model :detail, :person_id => :integer + define_model :person do + has_one :detail, :order => :id + end + Person.new.should @matcher.order(:id) + end + + it "should reject an association with a bad :order option" do + define_model :detail, :person_id => :integer + define_model :person do + has_one :detail + end + Person.new.should_not @matcher.order(:id) + end + end context "have_and_belong_to_many" do