lib/matchers/associations/associations.rb in mongoid-minitest-0.0.1 vs lib/matchers/associations/associations.rb in mongoid-minitest-0.0.2

- old
+ new

@@ -1,48 +1,48 @@ module Mongoid module Matchers module Associations - HAS_MANY = Mongoid::Relations::Referenced::Many + HAS_ONE = Mongoid::Relations::Referenced::One + HAS_MANY = Mongoid::Relations::Referenced::Many + BELONGS_TO = Mongoid::Relations::Referenced::In class HaveAssociationMatcher + include Helpers + def initialize(name, type) @association = {} @association[:name] = name.to_s @association[:type] = type - @expectation_message = "#{type_description} #{@association[:name].inspect}" + @description = "#{type_description} #{@association[:name].inspect}" end def of_type(klass) @association[:class] = klass - @expectation_message << " of type #{@association[:class].inspect}" + @description << " of type #{@association[:class].inspect}" self end - def matches?(klass) - @klass = klass.is_a?(Class) ? klass : klass.class + def matches?(subject) + @klass = class_of(subject) @metadata = @klass.relations[@association[:name]] @result = true check_association_name - check_association_type if @result - check_association_class if @result + check_association_type + check_association_class if @association[:class] @result end def failure_message - "Expected #{@klass} to #{@expectation_message}, got #{@negative_message}" + "#{@klass} to #{@description}, got #{@negative_message}" end def negative_failure_message - "Expected #{@klass} to not #{@expectation_message}, got #{@positive_message}" + "#{@klass} to not #{@description}, got #{@positive_message}" end - def description - @expectation_message - end - private def check_association_name if @metadata.nil? @negative_message = "no association named #{@association[:name]}" @@ -69,30 +69,42 @@ msg end def check_association_class - if !@association[:class].nil? and @association[:class] != @metadata.klass + if @association[:class] != @metadata.klass @negative_message = "#{@positive_message} of type #{@metadata.klass}" @result = false else @positive_message << " of type #{@metadata.klass}" if @association[:class] end end def type_description(type = nil, passive = true) type ||= @association[:type] case type.name + when HAS_ONE.name + (passive ? "reference" : "references") << " one" when HAS_MANY.name (passive ? "reference" : "references") << " many" + when BELONGS_TO.name + (passive ? "be referenced" : "referenced") << " in" else - raise "Unknown association type '%s'" % type + raise "Unknown association type #{type}" end end end + def have_one(association_name) + HaveAssociationMatcher.new(association_name, HAS_ONE) + end + def have_many(association_name) HaveAssociationMatcher.new(association_name, HAS_MANY) + end + + def belong_to(association_name) + HaveAssociationMatcher.new(association_name, BELONGS_TO) end end end end